[英]List comprehension - concatenate nth item from each sub-list
这个想法是从子列表中连接第 n 个项目,如下所示。 在这里,我想自动化这样一种方式,我不需要每次都根据原始列表的长度手动定义每个 ol[0] 或 ol[1]; 有什么可能吗?
例如,如果我的输入列表是:
[("a","b","c"),("A","B","C")]
期望的结果是:
['aA', 'bB', 'cC']
这是我当前执行此操作的代码:
ol = [("a","b","c"),("A","B","C")]
x=None
y=None
nL=[(x+y) for x in ol[0] for y in ol[1] if ol[0].index(x)==ol[1].index(y)]
print(nL)
您可以使用内置zip()
函数(此示例使用 f-string 连接列表内的字符串):
ol=[("a","b","c"),("A","B","C")]
print([f'{a}{b}' for a, b in zip(*ol)])
输出:
['aA', 'bB', 'cC']
zip
的星号*
将扩展可迭代对象,因此您不必手动对其进行索引。
要使其通用并连接多个值,您可以使用以下脚本:
ol=[("a","b","c"),("A","B","C"), (1, 2, 3), ('!', '@', '#')]
print([('{}' * len(ol)).format(*v) for v in zip(*ol)])
将打印:
['aA1!', 'bB2@', 'cC3#']
您可以使用zip()
来实现这一点:
>>> ol = [("a","b","c"),("A","B","C")]
# v to unpack the list
>>> nL = [''.join(x) for x in zip(*ol)]
# OR explicitly concatenate elements at each index
# >>> nL = [a+b for a, b in zip(*ol)]
>>> nL
['aA', 'bB', 'cC']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.