我有一个从列表列表返回列表的函数,其中返回列表按索引号对每个列表的成员进行分组。代码和示例:
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、生成器等让它更具Pythonic?我已经看过类似this的例子,但是在我的代码中没有与单个列表的元素进行交互。谢谢
使用
zip
和列表理解:用法:
类型注释的使用是可选的。你知道吗
在正常情况下,我也会使用
itertools.chain
,就像奥斯汀的回答一样。你知道吗但是,为了完整起见,一个不导入任何内容的替代解决方案:
输出:
使用^{} +^{} :
用法:
相关问题 更多 >
编程相关推荐