【发布时间】:2019-09-03 22:33:58
【问题描述】:
我有一个从列表列表返回列表的函数,其中返回列表按索引号对每个列表的成员进行分组。代码及示例:
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]
有没有办法使用 itertools、generators 等使这个更 Pythonic?我看过像this 这样的例子,但在我的代码中,单个列表的元素没有交互。谢谢
【问题讨论】:
-
如果列表的长度不同怎么办?那你有什么要求呢?
-
断言防止这种情况,它们不应该根据程序的逻辑
标签: python