简体   繁体   English

列表理解 - 连接每个子列表中的第 n 个项目

[英]List comprehension - concatenate nth item from each sub-list

The idea is to do concatenate of nth item from sub-list as below.这个想法是从子列表中连接第 n 个项目,如下所示。 Here I would like to automate such a way that I don't need to define each ol[0] or ol[1] manually each time depending upon length of the original list ie ol;在这里,我想自动化这样一种方式,我不需要每次都根据原始列表的长度手动定义每个 ol[0] 或 ol[1]; Any possibility?有什么可能吗?

For example, if my input list is:例如,如果我的输入列表是:

[("a","b","c"),("A","B","C")]

the desired result is as:期望的结果是:

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

Here's my current code to perform this:这是我当前执行此操作的代码:

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)

You can use builtin zip() function (this example is using f-string for concatenating the strings inside the lists):您可以使用内置zip()函数(此示例使用 f-string 连接列表内的字符串):

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

Output:输出:

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

The asterisk * in the zip will expands the iterable, so you don't have to index it by hand. zip的星号*将扩展可迭代对象,因此您不必手动对其进行索引。

To make it universal and concatenate multiple values, you can use this script:要使其通用并连接多个值,您可以使用以下脚本:

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

Will print:将打印:

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

You can use zip() to achieve this as:您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM