[英]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: 我可以通过一对for循环来实现:
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(输出)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.