简体   繁体   中英

Python List Comprehension: Affix strings from one list to the start of strings in another, for a list of lists

I have two lists and I want to use a list comprehension to create a list of lists. The first list has some prefixes and the second has some suffixes.

prefixes = ['t1_', 't0_']
suffixes = ['price', 'sales']

The list comprehension should return

output = [['t1_price', 't1_sales'],
          ['t0_price', 't0_sales']]

I am able to accomplish this with a pair of for loops:

output = []
for prefix in prefixes:
    pairs = []
    for suffix in suffixes:
        pairs.append(prefix + suffix)
    output.append(pairs)

But I think a list comprehension would improve my code's readability.

How can I accomplish this?

You can also achieve this using list comprehension

[[p+s for s in suffixes] for p in prefixes]
#[['t1_price', 't1_sales'], ['t0_price', 't0_sales']]

an alternative using a generator that does not require a nested comprehension

from itertools import product
[a+b for (a, b) in product(prefixes, suffixes)]

输出= [[x + y表示前缀中的x]表示后缀y] print(输出)

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