带有重复值和后缀的列表
我有一个清单,a
:
a = ['a','b','c']
并需要复制一些带有后缀的值_ind
(顺序很重要):
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']
我试过了:
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
或itertools.chain
嵌套式理解来做到这一点,但在大多数情况下,我希望使用一种易于理解的自定义生成器函数。
借助python3.3,您还可以使用“
yield from
生成器委派”使这种优雅的解决方案更加简洁:def mygen(lst): for item in lst: yield from (item, item + '_ind')