我有一个从列表列表返回列表的函数,其中返回列表按索引号对每个列表的成员进行分组。代码和示例:
def listjoinervar(*lists: list) -> list:
"""returns list of grouped values from each list
keyword arguments:
lists: list of input lists
"""
assert(len(lists) > 0) and (all(len(i) == len(lists[0]) for i in lists))
joinedlist = [None] * len(lists) * len(lists[0])
for i in range(0, len(joinedlist), len(lists)):
for j in range(0, len(lists[0])):
joinedlist[i//len(lists[0]) + j*len(lists[0])] = lists[i//len(lists[0])][j]
return joinedlist
a = ['a', 'b', 'c']
b = [1, 2, 3]
c = [True, False, False]
listjoinervar(a, b, c)
# ['a', 1, True, 'b', 2, False, 'c', 3, False]
Run Code Online (Sandbox Code Playgroud)
有没有办法使用itertools,generators等来使它更像Pythonic?我看像例子这样,但在我的代码没有互动的B / W各列表的元素。谢谢
使用itertools.chain.from_iterable+ zip:
from itertools import chain
def listjoinervar(*a):
return list(chain.from_iterable(zip(*a)))
Run Code Online (Sandbox Code Playgroud)
用法:
>>> a = ['a', 'b', 'c']
>>> b = [1, 2, 3]
>>> c = [True, False, False]
>>> listjoinervar(a, b, c)
['a', 1, True, 'b', 2, False, 'c', 3, False]
Run Code Online (Sandbox Code Playgroud)