Python将列表添加到仅包含元素的单个列表中
很抱歉标题不好,但我会在这里更好地解释 在下面的函数中Python将列表添加到仅包含元素的单个列表中,python,list,Python,List,很抱歉标题不好,但我会在这里更好地解释 在下面的函数中 def returnList(): list = [] for i in xrange(4): list.append(i) return list 它返回列表[0,1,2,3]。在另一个功能中 def returnAllLists(): totalList = [] for i in xrange(4): totalList.append(returnList()) return totalL
def returnList():
list = []
for i in xrange(4):
list.append(i)
return list
它返回列表[0,1,2,3]。在另一个功能中
def returnAllLists():
totalList = []
for i in xrange(4):
totalList.append(returnList())
return totalList
正如预期的那样,结果是。棘手的是我需要结果。当然,我可以轻松地将returnAllList的结果分配给另一个列表,并进行两个循环,然后将元素分别插入另一个列表中。但是,我认为可以采用一种更有效的方法,因为我的方法对于以不同方式分配相同的值而言,具有ON^2复杂性。有什么建议吗?使用extend代替append:
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]
完全符合您的要求。来自:
当然,这是假设您不能将append更改为extend。类似这样的内容:
In [17]: lis=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
In [18]: sum(lis,[])
Out[18]: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
非常感谢您提供的伟大而简单的答案,甚至是Totalist+=returnList
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
In [17]: lis=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
In [18]: sum(lis,[])
Out[18]: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
python 3.2
a=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
res=[i for v in a for i in v]
another method:
list(i.chain(*a))