带有重复值和后缀的列表

发布于 2021-01-29 19:02:45

我有一个清单,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解决方案?

关注者
0
被浏览
46
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以使其成为生成器:

    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.productitertools.starmapitertools.chain嵌套式理解来做到这一点,但在大多数情况下,我希望使用一种易于理解的自定义生成器函数。


    借助python3.3,您还可以使用“yield from生成器委派”使这种优雅的解决方案更加简洁:

    def mygen(lst):
        for item in lst:
            yield from (item, item + '_ind')
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看