列出并连接每个子列表中的第n项

2024-04-18 23:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

其思想是将子列表中的第n项连接起来,如下所示。在这里,我想自动化这样一种方式,我不需要每次根据原始列表的长度手动定义每个ol[0]或ol[1],即ol;有没有可能?你知道吗

例如,如果我的输入列表是:

[("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)

Tags: innone列表forindex定义nl方式
2条回答

您可以使用内置的zip()函数(本例使用f-string连接列表中的字符串):

ol=[("a","b","c"),("A","B","C")]
print([f'{a}{b}' for a, b in zip(*ol)])

输出:

['aA', 'bB', 'cC']

zip中的星号*将扩展iterable,因此您不必手动索引它。你知道吗

要使其通用并串联多个值,可以使用以下脚本:

ol=[("a","b","c"),("A","B","C"), (1, 2, 3), ('!', '@', '#')]
print([('{}' * len(ol)).format(*v) for v in zip(*ol)])

将打印:

['aA1!', 'bB2@', 'cC3#']

您可以使用^{}来实现以下目的:

>>> 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']

相关问题 更多 >