想法是将子列表中的第n个项目连接起来,如下所示。在这里,我想实现一种自动化,不需要根据原始列表的长度即ol每次手动定义每个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)
答案 0 :(得分:1)
您可以使用内置的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#']
答案 1 :(得分:0)
您可以使用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']