我想在pythonic for循环中生成更多元素。我怎样才能做到这一点?正常的代码是:
my_list = ['foo', 'bar']
li = []
for i in my_list:
li.extend(['a_' + i, 'b_' + i])
所以结果应该是:
['a_foo', 'b_foo', 'a_bar', 'b_bar']
谢谢!
答案 0 :(得分:2)
不太确定你在追求什么,但我会这样写:
foobar = ['foo', 'bar']
li = ['{}_{}'.format(y, x) for x in foobar for y in ['a', 'b']]
答案 1 :(得分:2)
如果您有两个列表,则可以使用itertools
product
from itertools import product
l = ['foo', 'bar']
add = ['a', 'b']
['_'.join(a) for a in product(add, l)]
['a_foo', 'a_bar', 'b_foo', 'b_bar']