Python TypeError:“int”对象不可iterable-for循环中计数器变量的功能是什么?
在本例中,我的for循环的初始值中的“num”在一个数字列表上迭代。我不明白为什么我会得到一个错误,一个int对象是不可编辑的?有人能解释一下这里的问题吗Python TypeError:“int”对象不可iterable-for循环中计数器变量的功能是什么?,python,python-2.7,for-loop,Python,Python 2.7,For Loop,在本例中,我的for循环的初始值中的“num”在一个数字列表上迭代。我不明白为什么我会得到一个错误,一个int对象是不可编辑的?有人能解释一下这里的问题吗 import random base_num = [] for _ in range(3): base_num.append(random.randint) while True: cow = 0 bull = 0 num_to_compare = input("what would you like to
import random
base_num = []
for _ in range(3):
base_num.append(random.randint)
while True:
cow = 0
bull = 0
num_to_compare = input("what would you like to guess?")
num_list = [int (d) for d in str(num_to_compare)]
if num_to_compare == base_num:
break
else:
for num in len(num_list):
for base in len(base_num):
if num_list[num] == base_num[num]:
cow += 1
elif num_list[num] == base_num[base]:
bull += 1
print cow, bull
对于lennum_列表中的num:
这本质上意味着3中的num:或num_列表中除3len以外的任何其他数字,它是一个int,不能被迭代。这就是错误告诉你的
您可能需要执行以下操作:
对于num_列表中的num:如果您希望迭代num_列表中的每个项目,或者
对于rangelennum_列表中的num:如果希望迭代索引
您可能还想阅读有关
这一行也是如此:
对于lenbase_num中的base:
此外,num_list=[strnum_to_compare中的int d for d]可以是num_list=[int d for d in num_to_compare],因为num_to_compare已经是str
编辑:
除此之外,正如@DYZ所评论的,如果通过这个:base_num.appendrandom.randint您希望在列表中添加一些随机数,那么它应该是base_num.appendrandom.randinta,b,在这里您将获得一个随机数N,这样arandom.randint必须是random.randint。此外,num_to_compare永远不等于base_num,因为一个是字符串,另一个是列表。