如何遍历一个列表的列表,例如:
[[1,2,3,4], [5,6], [7,8,9]]
通过获取每个列表的第一项、第二项等等,构建一个新列表,因此上面的内容变成了这样:
[1, 5, 7, 2, 6, 8, 3, 9, 4]
如何遍历一个列表的列表,例如:
[[1,2,3,4], [5,6], [7,8,9]]
通过获取每个列表的第一项、第二项等等,构建一个新列表,因此上面的内容变成了这样:
[1, 5, 7, 2, 6, 8, 3, 9, 4]
你可以使用列表推导式与 itertools.izip_longest
(或 Python 3 中的 zip_longest
)一起使用。
from itertools import izip_longest
a = [[1,2,3,4], [5,6], [7,8,9]]
[i for sublist in izip_longest(*a) for i in sublist if i is not None]
# [1, 5, 7, 2, 6, 8, 3, 9, 4]
None
不会出现,你就可以利用map()
在没有函数的情况下工作的方式:outlist = [y for sub in map(None, *inlist) for y in sub if not y is None]
itertools
有一个配方似乎非常适合这个任务:roundrobin
。from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
l = [[1,2,3,4], [5,6], [7,8,9]]
print (list(roundrobin(*l)))
#[1, 5, 7, 2, 6, 8, 3, 9, 4]
next
,而Python 3使用__next__
。 - chapelonext(iter(it))
对于两种情况都可以工作,对吗? - Paulfunctools.partial
或lambda。 - Kevin如果过滤掉None
,那么如果你想保留的子列表中有None
值,这种解决方案就不起作用了。为了解决这个问题,你可以使用列表推导式来迭代最长子列表的索引,并且只有在索引范围内时才添加子列表项。
a = [[1,2,3,4],[5,6,None],[7,8,9]]
range_longest = range(max(map(len, a)))
[sublist[i] for i in range_longest for sublist in a if i < len(sublist)]
# [1, 5, 7, 2, 6, 8, 3, None, 9, 4]
zip_longest
。 - pp_list(filter(lambda x: x is not None, chain(*zip_longest(*a))))
。 - Paul