【发布时间】:2013-03-11 23:44:07
【问题描述】:
我正在尝试编写一个程序,该程序生成一个包含 1-5 (含)的十个随机整数的列表,然后在每个整数重复时打印该数字。然后打印删除重复项的第二个列表。现在,我什至根本无法生成第一个列表。我不断收到 TypeError: 'int' object is not iterable
这是我目前所拥有的:
def randomTen():
"""return list of ten integers and the number of times each one
appears"""
firstList= []
for num in range(1,11):
x= int(random.randint(1,6))
list1= firstList.append(x)
print(list1)
【问题讨论】:
-
你想要
append,而不是extend。 -
谢谢。我改变了它,但现在它只返回“无”
-
是的,这就是 append() 的工作原理。它更改源列表(“firstList”)并且不返回任何内容。
-
此外,您的函数将继续返回
None,直到您返回带有return关键字的内容。 -
也就是说,像
firstList = [random.randint(1,6) for num in range(10)]这样的列表理解是一种更“pythonic”的方式来做同样的事情。
标签: python