在Python中的函数中连接任意数量的列表 [英] concatenate an arbitrary number of lists in a function in Python

查看:101
本文介绍了在Python中的函数中连接任意数量的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望编写join_lists函数以获取任意数量的列表并将其连接起来.例如,如果输入为

I hope to write the join_lists function to take an arbitrary number of lists and concatenate them. For example, if the inputs are

m = [1, 2, 3]
n = [4, 5, 6]
o = [7, 8, 9]

然后我们称为print join_lists(m, n, o),它将返回[1, 2, 3, 4, 5, 6, 7, 8, 9].我意识到我应该使用*args作为join_lists中的参数,但是不确定如何连接任意数量的列表.谢谢.

then we I call print join_lists(m, n, o), it will return [1, 2, 3, 4, 5, 6, 7, 8, 9]. I realize I should use *args as the argument in join_lists, but not sure how to concatenate an arbitrary number of lists. Thanks.

推荐答案

一种方法是这种方法(使用reduce),因为我目前感觉很正常:

One way would be this (using reduce) because I currently feel functional:

import operator
from functools import reduce
def concatenate(*lists):
    return reduce(operator.add, lists)

但是,Marcin的答案给出了一种更好的功能方法:

However, a better functional method is given in Marcin's answer:

from itertools import chain
def concatenate(*lists):
    return chain(*lists)

尽管您最好直接使用 itertools.chain(*iterable_of_lists)

although you might as well use itertools.chain(*iterable_of_lists) directly.

一种程序方式:

def concatenate(*lists):
    new_list = []
    for i in lists:
        new_list.extend(i)
    return new_list

打高尔夫球的版本:j=lambda*x:sum(x,[])(请勿实际使用).

A golfed version: j=lambda*x:sum(x,[]) (do not actually use this).

这篇关于在Python中的函数中连接任意数量的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆