aList = []
for number in range (1,11):
aList += [number]
print ("printing",aList);
输出是: 印花 [1,2,3,4,5,6,7,8,9,10]
但如果我这样修改(我希望将100添加到列表的末尾)
aList = []
for number in range (1,11):
aList += [number]
aList += 100;
print ("printing",aList);
我收到此错误: TypeError:' int'对象不可迭代
答案 0 :(得分:3)
您当前的代码有三个问题:
aList += 100
应为aList += [100]
aList += [100]
应移至for循环之外例如:
在[2]中:
aList = []
for number in range (1,11):
aList += [number]
aList += [100]
print ("printing",aList) # ('printing', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100])
你也可以这样做:
print ("printing", range(1, 11) + [100]) # ('printing', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100])
答案 1 :(得分:1)
如果您不想在列表中使用.append()
:
aList = []
for number in range (1,11):
aList += [number]
aList += [100]
print ("printing",aList)
请注意,您不需要在行尾添加分号(;
)
答案 2 :(得分:1)
范围返回一个列表,因此这足以代替for循环
aList = range(1, 11)
添加' 100'作为最后一个元素,再添加一个语句
aList += [100]
或
aList.append(100)
答案 3 :(得分:-1)
range
是一个列表。因此,您可以这样做:
aList = range(10) + [100]