Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:“int”对象不可iterable-for循环中计数器变量的功能是什么?_Python_Python 2.7_For Loop - Fatal编程技术网

Python TypeError:“int”对象不可iterable-for循环中计数器变量的功能是什么?

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

在本例中,我的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 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,因为一个是字符串,另一个是列表。