简体   繁体   中英

List comprehension - concatenate nth item from each sub-list

The idea is to do concatenate of nth item from sub-list as below. 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; 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):

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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