TypeError:“tuple”对象不能解释为整数

2024-04-20 05:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个超级基本的进化模拟器,生成十个随机的“生物”,每个都是一个数字值,然后给它们一个随机的“变异”,但它不断地向我抛出这个错误:“对于我在范围内(生物): TypeError:“tuple”对象不能解释为整数

import random
from random import randint

creatures = (random.randint(1, 10), random.randint(1, 10))

print(creatures)

for i in range(creatures):
    mutation = random.randint(1, 2)
    newEvolution = creatures[i] + mutation

print("New evolution", newEvolution)

Tags: import错误生物数字random模拟器printrandint
3条回答

你需要在生物的长度范围内迭代。

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)

生物是一个tuple,而range正在寻找一个整数。要遍历元组,只需执行以下操作:

for c in creatures:
    mutation = random.randint(1, 2)
    newEvolution = c + mutation

相关问题 更多 >