[英]Appending a new value to python list
aList = []
for number in range (1,11):
aList += [number]
print ("printing",aList);
Output is: printing [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 输出为:打印[1、2、3、4、5、6、7、8、9、10]
but if I modify like this (I expect 100 to be added to the end of the list) 但是如果我这样修改(我希望将100添加到列表的末尾)
aList = []
for number in range (1,11):
aList += [number]
aList += 100;
print ("printing",aList);
I get this error: TypeError: 'int' object is not iterable 我收到此错误: TypeError:'int'对象不可迭代
You have three problems with your current code: 您当前的代码存在三个问题:
aList += 100
should be aList += [100]
aList += 100
应该是aList += [100]
aList += [100]
should be moved to outside the for loop aList += [100]
应该移到for循环之外 For example: 例如:
In [2]: 在[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])
You could also simply this to: 您也可以简单地这样做:
print ("printing", range(1, 11) + [100]) # ('printing', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100])
If you don't want to use .append()
on a list: 如果您不想在列表上使用
.append()
:
aList = []
for number in range (1,11):
aList += [number]
aList += [100]
print ("printing",aList)
Please note that you don't need the semicolon at the end of the line ( ;
) 请注意,您不需要在行尾(
;
)处使用分号;
range returns a list, hence this much is sufficient instead of for loop range返回一个列表,因此这足以代替for循环
aList = range(1, 11)
to add '100' as last element, add one more statement 要添加“ 100”作为最后一个元素,请再添加一条语句
aList += [100]
or 要么
aList.append(100)
range
is a list. range
是一个列表。 Hence, you can just do: 因此,您可以执行以下操作:
aList = range(10) + [100]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.