[英]Python 3, and slice operand with comma
I came to a notation in python where I iterate len(nums) like this: where我在 python 中找到了一个符号,在这里我像这样迭代 len(nums):
res = []
res += nums[i]
and I get the TypeError: 'int' object is not iterable
error message.我得到TypeError: 'int' object is not iterable
错误消息。 However, If I do,但是,如果我这样做,
res += nums[i],
the expression passes.表达式通过。 I tried to look Python doc, but couldn't find the reference.我试图查看 Python 文档,但找不到参考。 Can you please help me locate it or explain why I need a comma for slice iteration additions?你能帮我找到它或解释为什么我需要一个逗号来添加切片迭代吗?
Your nums
list is probably a 1d list, let's say the list is:您的nums
列表可能是一维列表,假设列表是:
nums = [1, 2, 3]
Then when you index the nums
list:然后,当您索引nums
列表时:
nums[i]
It will give you a value of 1
or 2
or 3
.它会给你一个1
或2
或3
的值。
But single values can't be added to a list:但是不能将单个值添加到列表中:
>>> [] + 1
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
[] + 1
TypeError: can only concatenate list (not "int") to list
>>>
But your second code works because adding a comma makes a single value into a tuple, like below:但是您的第二个代码有效,因为添加逗号会使单个值成为元组,如下所示:
>>> 1,
(1,)
>>>
So of course:所以当然:
>>> res = []
>>> res += (1,)
>>> res
[1]
>>>
Works.作品。
It doesn't only work with ,
comma, if you do:如果您这样做,它不仅适用于,
逗号:
>>> res = []
>>> res += [1]
>>> res
[1]
>>>
It will work too.它也会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.