我一直在试图弄清楚如何编写一个函数来连接使用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)
答案 0 :(得分:8)
itertools
救援!
def join_lists(*args):
return list(itertools.chain(*args))
答案 1 :(得分: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]
答案 2 :(得分: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]
>>>
答案 3 :(得分: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