使用 += 通过 while 循环填充列表给我一个错误
using += to populate a list through while loop gives me an error
我有一个非常基本的理解,即 +=
和 .append
在将新元素添加到列表方面非常相似。但是,当我尝试通过 while
循环用随机整数值填充列表时,我发现它们的表现不同。 append
运行良好,但是,运行 我使用 +=
的程序会给我一个错误:
TypeError: 'int' 对象不可迭代
这是我的代码:
1.use +=
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list += random.randint(0,10)
i = i + 1
print random_list
**TypeError: 'int' object is not iterable**
2.use .append
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list.append(random.randint(0,10))
i = i + 1
print random_list
**[4, 7, 0, 6, 3, 0, 1, 8, 5, 10, 9, 3, 4, 6, 1, 1, 4, 0, 10, 8]**
有谁知道为什么会这样?
发生这种情况是因为 +=
用于将一个列表附加到另一个列表的末尾,而不是用于附加一个项目。
这是做的简短版本:
items = items + new_value
如果 new_value
不是列表,这将失败,因为您不能使用 +
将项目添加到列表。
items = items + 5 # Error: can only add two list together
解决方法是将值做成一个单项长列表:
items += [value]
或使用 .append
- 将单个项目添加到列表的首选方式。
是的,这很棘手。只需在 random.randint(0, 10)
末尾添加一个 ,
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list += random.randint(0, 10),
i += 1
print random_list
它将打印:
[4, 7, 7, 10, 0, 5, 10, 2, 6, 2, 6, 0, 2, 7, 5, 8, 9, 8, 0, 2]
您可以找到更多关于尾随 ,
的 explanation
我有一个非常基本的理解,即 +=
和 .append
在将新元素添加到列表方面非常相似。但是,当我尝试通过 while
循环用随机整数值填充列表时,我发现它们的表现不同。 append
运行良好,但是,运行 我使用 +=
的程序会给我一个错误:
TypeError: 'int' 对象不可迭代
这是我的代码:
1.use +=
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list += random.randint(0,10)
i = i + 1
print random_list
**TypeError: 'int' object is not iterable**
2.use .append
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list.append(random.randint(0,10))
i = i + 1
print random_list
**[4, 7, 0, 6, 3, 0, 1, 8, 5, 10, 9, 3, 4, 6, 1, 1, 4, 0, 10, 8]**
有谁知道为什么会这样?
发生这种情况是因为 +=
用于将一个列表附加到另一个列表的末尾,而不是用于附加一个项目。
这是做的简短版本:
items = items + new_value
如果 new_value
不是列表,这将失败,因为您不能使用 +
将项目添加到列表。
items = items + 5 # Error: can only add two list together
解决方法是将值做成一个单项长列表:
items += [value]
或使用 .append
- 将单个项目添加到列表的首选方式。
是的,这很棘手。只需在 random.randint(0, 10)
,
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list += random.randint(0, 10),
i += 1
print random_list
它将打印:
[4, 7, 7, 10, 0, 5, 10, 2, 6, 2, 6, 0, 2, 7, 5, 8, 9, 8, 0, 2]
您可以找到更多关于尾随 ,