Python 类型错误:';元组';对象不能解释为整数;
我正试图制作一个超级基本的进化模拟器,生成十个随机的“生物”,每个都是一个数值,然后给它们一个随机的“变异”,但它总是给我这个错误:“因为我在范围内(生物): TypeError:“tuple”对象不能解释为整数”Python 类型错误:';元组';对象不能解释为整数;,python,Python,我正试图制作一个超级基本的进化模拟器,生成十个随机的“生物”,每个都是一个数值,然后给它们一个随机的“变异”,但它总是给我这个错误:“因为我在范围内(生物): TypeError:“tuple”对象不能解释为整数” 生物是一个元组,而范围正在寻找一个整数。要迭代元组,只需执行以下操作: for c in creatures: mutation = random.randint(1, 2) newEvolution = c + mutation 你需要在生物的长度范围内迭代 fr
生物是一个
元组
,而范围
正在寻找一个整数。要迭代元组,只需执行以下操作:
for c in creatures:
mutation = random.randint(1, 2)
newEvolution = c + mutation
你需要在生物的长度范围内迭代
from random import randint
creatures = (random.randint(1, 10), random.randint(1, 10))
print(creatures)
for i in range(len(creatures)): # iterate over the range of the lenght of the creatures
mutation = random.randint(1, 2)
newEvolution = creatures[i] + mutation
print("New evolution", newEvolution)
这些生物是一个元组和range()函数,因为参数接受整数
Syntax for range:
range([start], stop[, step])
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.
Note that:
All parameters must be integers.
解决方案:
import random
creatures = random.sample(range(1, 11), 10)
print(creatures)
newEvolution = []
for i in range(len(creatures)):
mutation = random.randint(1, 2)
newEvolution.append(creatures[i] + mutation)
print("New evolution", newEvolution)
感谢您没有为范围内的i(len(someseq))推广
的反模式:
和显式索引。:-)
import random
creatures = random.sample(range(1, 11), 10)
print(creatures)
newEvolution = []
for i in range(len(creatures)):
mutation = random.randint(1, 2)
newEvolution.append(creatures[i] + mutation)
print("New evolution", newEvolution)