简体   繁体   English

append 列表列表 python

[英]append list of lists in python

I am trying to append a list of lists with Python but there is an error.我正在尝试 append 列表列表 Python 但出现错误。 My problem is just with append function. I explain my problem better.我的问题只是 append function。我更好地解释了我的问题。 I am using a loop.我正在使用一个循环。 The first time the append function works fine. append function 第一次工作正常。 But for the second time, the function does not work.但是第二次,function不起作用。

When we do the first loop, we get the right result:当我们执行第一个循环时,我们得到正确的结果:

list1 = [1,2,3]
list2  = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)

result:结果:

[[1, 2, 3], [4, 5, 6]]

With the second loop, append does not work correctly.在第二个循环中,append 无法正常工作。 One extra bracket.一个额外的支架。

liste4 = []
liste4.append(list3)
liste4.append(list1)
print(liste4)

result:结果:

[[[1, 2, 3], [4, 5, 6]], [1, 2, 3]]

But the result I want is this:但我想要的结果是这样的:

[[1, 2, 3], [4, 5, 6], [1, 2, 3]]

Define list3 as an empty list and append to it:将 list3 定义为空列表并将 append 定义为它:

list1 = [1,2,3]
list2  = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)

Output: Output:

[[1, 2, 3], [4, 5, 6]]

you could just do list3 = [list1, list2]你可以做list3 = [list1, list2]

If you want it in a function, here is a go aa List of List creator, which may take multiple lists as the input:如果你想要它在一个 function 中,这里有一个 go aa List of List creator,它可能需要多个列表作为输入:

def LoL(*lists):
    out = [x for x in lists]
    return out

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]

list4 = LoL(list1,list2,list3)
list4
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list1 = [1,2,3]
list2  = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)

result:结果:

[[1, 2, 3], [4, 5, 6]]

With the second loop:在第二个循环中:

liste4 = list3
liste4.append(list1)
print(liste4)

result:结果:

[[1, 2, 3], [4, 5, 6], [1, 2, 3]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM