Duplicate elements in a list

前端 未结 6 1093
滥情空心
滥情空心 2020-12-10 02:28

I have a list in Python:

l = [\'a\', \'c\', \'e\', \'b\']

I want to duplicate each element immediately next to the original.

相关标签:
6条回答
  • 2020-12-10 02:59
    import itertools
    
    ll = list(itertools.chain.from_iterable((e, e) for e in l))
    

    At work:

    >>> import itertools
    >>> l = ['a', 'c', 'e', 'b']
    >>> ll = list(itertools.chain.from_iterable((e, e) for e in l))
    >>> ll
    ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
    

    As Lattyware pointed out, in case you want more than just double the element:

    from itertools import chain, repeat
    
    ll = list(chain.from_iterable(repeat(e, 2) for e in l))
    
    0 讨论(0)
  • 2020-12-10 03:03
    >>> l = ['a', 'c', 'e', 'b']
    >>> [x for pair in zip(l,l) for x in pair]
    ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
    

    Or

    >>> from itertools import repeat
    >>> [x for item in l for x in repeat(item, 2)]
    ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
    
    0 讨论(0)
  • 2020-12-10 03:05

    Here's a pretty easy way:

    sum(zip(l, l), tuple())
    

    It duplicates each item, and adds them to a tuple. If you don't want a tuple (as I suspect), you can call list on the the tuple:

    list(sum(zip(l, l), tuple()))
    

    A few other versions (that yield lists):

    list(sum(zip(l, l), ()))
    
    sum([list(i) for i in zip(l, l)], [])
    
    sum(map(list, zip(l, l)), [])
    
    0 讨论(0)
  • 2020-12-10 03:06

    Try this

    for i in l:
        ll.append(i)
        ll.append(i)
    

    Demo

    It will just do your work but it's not an optimized way of doing this.

    use the ans. posted by @Steven Rumbalski

    0 讨论(0)
  • 2020-12-10 03:10

    This is old but I can't see the straightforward option here (IMO):

    [ item for item in l for repetitions in range(2) ]
    

    So for the specific case:

    >>> l = ['a', 'c', 'e', 'b']
    l = ['a', 'c', 'e', 'b']
    >>> [ i for i in l for r in range(2) ]
    [ i for i in l for r in range(2) ]
    ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
    >>> 
    

    And generalizing:

    [ item for item in l for _ in range(r) ] 
    

    Where r is the quantity of repetitions you want.

    So this has a O(n.r) space and time complexity, is short, with no dependencies and also idiomatic.

    0 讨论(0)
  • 2020-12-10 03:13

    Pandas gives a method for duplicated elements:

    import pandas as pd
    l = pd.Series([2, 1, 3, 1])
    print(l.duplicated())
    >>>0    False
       1    False
       2    False
       3     True
       dtype: bool
    
    print('Has list duplicated ? :', any(l.duplicated()))
    >>>Has list duplicated ? : True
    
    0 讨论(0)
提交回复
热议问题