Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多个列表合并到一个列表中_Python_List - Fatal编程技术网

Python 将多个列表合并到一个列表中

Python 将多个列表合并到一个列表中,python,list,Python,List,这就是我所拥有的: list1 = ['a', 'b', 'c'] list2 = ['d', 'e', 'f'] list3 = ['g', 'h', 'i'] 这就是我想要的: list4 = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']] 如何解决这个问题 res = [] for l in (lis1, list2, list3): res.extend(l) 这将为您提供另一个名为res的列表,它是这三个子列表的“奉承”

这就是我所拥有的:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']
这就是我想要的:

list4 = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]
如何解决这个问题

res = []
for l in (lis1, list2, list3):
    res.extend(l)

这将为您提供另一个名为
res
的列表,它是这三个子列表的“奉承”表示。

要创建这样的列表,只需使用:

list4 = [list1, list2, list3]

您应该只简单地将列表放到另一个列表中:
list4=[list1,list2,list3]
。结果将是一个二维列表(如您所期望的)

完整代码:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

list4 = [list1, list2, list3]

print("Result: {}".format(list4))
>>> python3 test.py
Result: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
输出:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

list4 = [list1, list2, list3]

print("Result: {}".format(list4))
>>> python3 test.py
Result: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

你的意思是
list4=[list1,list2,list3]
?@khelwood这看起来很像,但我需要在列表分配时这样做,我需要在循环中这样做。如何解决这个问题?你必须详细说明你的实际情况,特别是为什么你有一堆单独编号变量的列表。list4=[list1,list2,list3]将工作人员作为一个复制品关闭此项:这似乎与提问者的期望不符。提问者想要得到一个2D列表。但在您的情况下,这些列表将被合并,结果将是一个1D列表(
['a'、'b'、'c'、'd'、'e'、'f'、'g'、'h'、'i']
)。此外,迭代器中有一个输入错误(
lis1
而不是
list1
)。