带有重复值和后缀的列表 [英] List with duplicated values and suffix
问题描述
我有一个列表,a
:
a = ['a','b','c']
,并且需要使用添加的后缀_ind
重复某些值(顺序很重要):
and need to duplicate some values with the suffix _ind
added this way (order is important):
['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解决方案?
Is there some better, more pythonic solution?
推荐答案
您可以使其成为生成器:
You could make it a generator:
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
或嵌套的理解来做到这一点,但在大多数情况下,我希望使用一种易于理解的自定义生成器函数.
You could also do it with itertools.product
, itertools.starmap
or itertools.chain
or nested comprehensions but in most cases I would prefer a simple to understand, custom generator-function.
使用python3.3,您还可以使用yield from
(生成器委派)使这种优雅的解决方案更加简洁:
With python3.3, you can also use yield from
—generator delegation—to make this elegant solution just a bit more concise:
def mygen(lst):
for item in lst:
yield from (item, item + '_ind')
这篇关于带有重复值和后缀的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!