我有一个清单,a
:
a = ['a','b','c']
并且需要使用后缀重复一些值_ind
这样添加(顺序很重要):
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']
I tried:
b = [[x, x + '_ind'] for x in a]
c = [item for sublist in b for item in sublist]
print (c)
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']
有没有更好、更Pythonic的解决方案?
你可以把它变成一个生成器:
def mygen(lst):
for item in lst:
yield item
yield item + '_ind'
>>> a = ['a','b','c']
>>> list(mygen(a))
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']
你也可以这样做itertools.product
, itertools.starmap
or itertools.chain
或嵌套理解,但在大多数情况下,我更喜欢一个简单易懂的自定义生成器函数。
使用python3.3,还可以使用yield from
- 生成器委托 - 让这个优雅的解决方案更加简洁:
def mygen(lst):
for item in lst:
yield from (item, item + '_ind')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)