Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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_Python 3.x_List_Concatenation - Fatal编程技术网

连接作为参数传递给Python函数的多个列表的更快方法?

连接作为参数传递给Python函数的多个列表的更快方法?,python,python-3.x,list,concatenation,Python,Python 3.x,List,Concatenation,因此,我有一个函数,它将可变数量的列表作为参数,然后将这些列表合并到一个列表中: def comb_lists(*lists): sublist = [] for l in lists: sublist.extend(l) print(sublist) >>> comb_lists([1, 2], [3, 4], [5, 6]) [1, 2, 3, 4, 5, 6] 它是有效的。但我只是想知道是否有更简单的解决方案?我尝试使用

因此,我有一个函数,它将可变数量的列表作为参数,然后将这些列表合并到一个列表中:

def comb_lists(*lists):
    sublist = []
    for l in lists:
        sublist.extend(l)
    print(sublist)
    
>>> comb_lists([1, 2], [3, 4], [5, 6])
[1, 2, 3, 4, 5, 6]
它是有效的。但我只是想知道是否有更简单的解决方案?我尝试使用列表解包进行列表理解,但返回了一个语法错误:

def comb_lists(*lists):
    sublist = [*l for l in lists]
    
>>> comb_lists([1, 2], [3, 4], [5, 6])
SyntaxError: iterable unpacking cannot be used in comprehension
有没有更整洁或更快的方法

EDIT:itertools看起来对这类事情非常有用。我很想知道是否有不依赖于导入的方法。

模块中有内置函数来实现这一点:

>>> from itertools import chain
>>> my_list = [[1, 2], [3, 4], [5, 6]]

>>> list(chain.from_iterable(my_list))
[1, 2, 3, 4, 5, 6]
如果不想导入任何模块,可以编写嵌套列表理解以实现此目的,如下所示:

>>> my_list = [[1, 2], [3, 4], [5, 6]]

>>> [e for l in my_list for e in l]
[1, 2, 3, 4, 5, 6]
模块中有一个内置函数来执行此操作:

>>> from itertools import chain
>>> my_list = [[1, 2], [3, 4], [5, 6]]

>>> list(chain.from_iterable(my_list))
[1, 2, 3, 4, 5, 6]
如果不想导入任何模块,可以编写嵌套列表理解以实现此目的,如下所示:

>>> my_list = [[1, 2], [3, 4], [5, 6]]

>>> [e for l in my_list for e in l]
[1, 2, 3, 4, 5, 6]

这是最简单的解决方案

result = sum(lists, [])

这是最简单的解决方案

result = sum(lists, [])

试试
list(itertools.chain(*lists))
?试试
list(itertools.chain(*lists))
?谢谢!我很想知道是否有其他解决方案不使用导入,但这是一个有用的答案nevertheless@Lou更新了基于列表理解的解决方案谢谢!我很想知道是否有其他解决方案不使用导入,但这是一个有用的答案nevertheless@Lou更新了基于列表理解的解决方案,非常优雅,效果完美!但是为什么它会起作用呢?为什么sum函数不把列表的内容相加呢?@Lou如果给出了第二个参数,那么sum函数会把iterable的值一个接一个地加到第二个参数上。“列表”实际上是列表的列表,这就是为什么它没有添加内容。裁判:这非常优雅,效果非常好!但是为什么它会起作用呢?为什么sum函数不把列表的内容相加呢?@Lou如果给出了第二个参数,那么sum函数会把iterable的值一个接一个地加到第二个参数上。“列表”实际上是列表的列表,这就是为什么它没有添加内容。裁判: