合并列表中的元素:好像python以两种不同的方式对待同一个项目,我不知道为什么 [英] Combining elements in list: seems like python treats the same item in two different ways and I don't know why
问题描述
我正在通过CodeAcademy进行工作,并且我有一个未解决的问题.任务是获取列表列表,并为其所有元素制作一个列表.下面的代码是我的工作的答案.但是我不明白的是为什么项目"被视为该代码列表中的元素,而(请参见下面的注释)...
I'm working my way through CodeAcademy and I have a question that's going unanswered there. The assignment is to take a list of lists and make a single list of all its elements. The code immediately below is my answer that worked. But what I don't understand is why "item" is treated as elements in a list for that code whereas (see comment continued below)...
m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]
def join_lists(*args):
new_list = []
for item in args:
new_list += item
return new_list
print join_lists(m, n, o)
...下面的代码中的项目"被视为整个列表,而不是列表中的元素.下面的代码给出了输出:
...the "item" in the code below is treated as the whole list instead of elements in a list. The code below gives the ouput:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我还尝试使用: new_list.append(item [0:] [0:]),认为它会遍历索引和子索引,但结果相同.我只是不明白这是怎么解释的.
I also tried to use: new_list.append(item[0:][0:]) thinking it would iterate through the index and sub-index but it gave the same result. I just don't understand how this is being interpreted.
m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]
def join_lists(*args):
new_list = []
for item in args:
new_list.append(item)
return new_list
print join_lists(m, n, o)
此外,我知道我可以在上面的代码中添加另一个for循环,并且我知道为什么可以这样做,但是我仍然不明白为什么Python会以不同的方式解释它们.
Also, I know I could add another for-loop to the code above, and I get why that works, but I still don't understand with one line of difference why Python interprets these differently.
推荐答案
The +=
in-place add operator on a list does the same thing as calling list.extend()
on new_list
. .extend()
takes an iterable and adds each and every element to the list.
list.append()
将单个项添加到列表中.
>>> lst = []
>>> lst.extend([1, 2, 3])
>>> lst
[1, 2, 3]
>>> lst.append([1, 2, 3])
>>> lst
[1, 2, 3, [1, 2, 3]]
这篇关于合并列表中的元素:好像python以两种不同的方式对待同一个项目,我不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!