list.extend and list comprehension

后端 未结 6 1786
北恋
北恋 2020-12-10 01:05

When I need to add several identical items to the list I use list.extend:

a = [\'a\', \'b\', \'c\']
a.extend([\'d\']*3)

Result



        
相关标签:
6条回答
  • 2020-12-10 01:09
    >>> a = [['a',2], ['b',2], ['c',1]]
    >>> sum([[item]*count for item,count in a],[])
    ['a', 'a', 'b', 'b', 'c']
    
    0 讨论(0)
  • 2020-12-10 01:12
    import operator
    a = [['a',2], ['b',2], ['c',1]]
    nums = [[x[0]]*x[1] for x in a]
    nums = reduce(operator.add, nums)
    
    0 讨论(0)
  • 2020-12-10 01:25

    If you prefer extend over list comprehensions:

    a = []
    for x, y in l:
        a.extend([x]*y)
    
    0 讨论(0)
  • 2020-12-10 01:29
    >>> a = [['a',2], ['b',2], ['c',1]]
    >>> [i for i, n in a for k in range(n)]
    ['a', 'a', 'b', 'b', 'c']
    
    0 讨论(0)
  • 2020-12-10 01:32

    Stacked LCs.

    [y for x in a for y in [x[0]] * x[1]]
    
    0 讨论(0)
  • 2020-12-10 01:33

    An itertools approach:

    import itertools
    
    def flatten(it):
        return itertools.chain.from_iterable(it)
    
    pairs = [['a',2], ['b',2], ['c',1]]
    flatten(itertools.repeat(item, times) for (item, times) in pairs)
    # ['a', 'a', 'b', 'b', 'c']
    
    0 讨论(0)
提交回复
热议问题