【问题标题】:I'd like to make the python's list to ['a','a','b',b','c','c'] from ['a','b','c'] [duplicate]我想将python的列表从 ['a','b','c'] 变成 ['a','a','b',b','c','c'] [重复]
【发布时间】:2017-08-26 11:38:09
【问题描述】:

我想将 python 的列表从 ['a','b','c' 变成 ['a','a','b',b','c','c'] ].

有人知道这样做吗? 谢谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    对于或多或少说“我想重复每个元素两次”的内容,可以使用 range 的嵌套列表理解:

    >>> l = ['a', 'b', 'c']
    >>> [x for x in l for _ in range(2)]
    ['a', 'a', 'b', 'b', 'c', 'c']
    

    如果您发现列表乘法更具可读性并且不需要将 2 扩展为大数并将列表推导式转换为生成器表达式,则可以使用列表乘法将其缩短一点:

    >>> l = ['a', 'b', 'c']
    >>> [y for x in l for y in [x, x]]
    

    如果你是 Haskell 的粉丝,l >>= replicate 2 可以用,你可以模仿一下:

    import itertools
    from functools import partial
    from operator import mul
    
    
    def flat_map(iterable, f):
        return itertools.chain.from_iterable(map(f, iterable))
    
    
    l = ['a', 'b', 'c']
    flat_map(l, partial(mul, 2))
    

    【讨论】:

    • 你知道这个答案是否比我的运行得快吗?只是好奇,谢谢。
    • @KillPinguin:我没有,抱歉。
    【解决方案2】:

    您总是可以创建一个新列表:

    for x in oldList: 
      newList.append(x)
      newList.append(x)
    

    请注意,这将创建一个新列表,而不是修改旧列表!

    【讨论】:

      【解决方案3】:
      source = ['a','b','c']
      result = [el for el in source for _ in (1, 2)]
      print(result)
      

      给你

      ['a', 'a', 'b', 'b', 'c', 'c']
      

      【讨论】:

        最近更新 更多