Python 3.8“试图将int添加到列表中时,TypeError:'int'对象不可迭代”

问题描述 投票:1回答:3

我正在制作一个程序,它会生成一个从1到100的随机数,然后,如果该数字还没有出现在列表中,它将添加到列表中,并一直这样做,直到列表中有100个唯一数字为止。到目前为止,这是我的代码:

from random import randint
numbers = []
loop = True
while loop == True:
  number = randint(1, 100)
  if number in numbers:
      print("{} is there already!".format(number))
  else:
    numbers += number

但是它一直给我这个错误:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    numbers += number
TypeError: 'int' object is not iterable

但是,我敢肯定,我的代码没有错。我该怎么办?

python list int typeerror
3个回答
1
投票

只需将numbers += number替换为numbers.append(number)


1
投票

如果只想创建一个从1到100的唯一数字的随机排列的列表,则>]

这可能是更有效的代码

my_list = list(range(1,101))
random.shuffle(my_list)
print(my_list)

您可以修复随机种子,以便随机播放输出,但每次运行都不会更改

my_list = list(range(1,101))
random.seed(123)
random.shuffle(my_list, random=None)
print(my_list)

对于您的代码,您不能对列表使用+=进行.append(将您的数字作为参数并将其添加到列表的末尾)

numbers.append(number)

DOCS:https://docs.python.org/2/tutorial/datastructures.html


0
投票

我认为您正在尝试从1至100中随机添加数字,并在数字列表中随机添加,并且您不想多次添加任何内容

© www.soinside.com 2019 - 2024. All rights reserved.