0

我一直在试图弄清楚如何编写一个函数来连接任意数量的使用 splat 的列表。

下面的代码是最接近我想要的位置的代码,但我试图让函数输出一个如下所示的列表:

[1,2,3,4,5,6,7,8,9]

但我只结束了它显示为三个嵌套列表。任何帮助将非常感激。谢谢你。

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

# Update the below function to take
# an arbitrary number of arguments
def join_lists(*args):
    return args


print join_lists(m, n, o)
4

4 回答 4

8

itertools救援!

def join_lists(*args):
    return list(itertools.chain(*args))
于 2013-08-27T05:40:06.957 回答
2

万一您想手动编写代码:)

>>> def joinlists(*args):
...     l = []
...     for arg in args:
...             l.extend(arg)
...     return l
... 
>>> joinlists(m, n, o)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

或这个 :-

>>> def joinlists(*args):
...     l = []
...     for arg in args:
...         for item in arg:
...             l.append(item)
...     return l
... 
>>> joinlists(m, n, o)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
于 2013-08-27T05:47:21.387 回答
2

您可以使用reduce(lambda x,y: x+y, args)

>>> m = [1, 2, 3]
>>> n = [4, 5, 6]
>>> o = [7, 8, 9]
>>>
>>> def join_lists(*args):
...     return reduce(lambda x,y: x+y, args)
...
>>> join_lists(m,n,o)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

reduce(operator.add, args)

>>> import operator
>>>
>>> m = [1, 2, 3]
>>> n = [4, 5, 6]
>>> o = [7, 8, 9]
>>>
>>> def join_lists(*args):
...     return reduce(operator.add, args)
...
>>> print join_lists(m,n,o)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
于 2013-08-27T06:03:00.387 回答
2

鉴于您仅限于“基本”功能(如最近的评论中所披露),这是一个简短的列表理解:

def join_lists(*args):
    return [i for L in args for i in L]

或者,展开为嵌套循环(完全等效):

def join_lists(*args):
    out = []
    for L in args:
        for i in L:
            out.append(i)
    return out
于 2013-08-27T06:07:33.467 回答