【问题标题】:Transform a python list to [[index] * value ] flattened将 python 列表转换为 [[index] * value ] 展平
【发布时间】:2021-11-26 22:18:28
【问题描述】:

我有一个列表,并且想将列表转换为 [[index] * value] 扁平化。

例如,如果输入为[1, 2, 3, 1],则输出应为[0, 1, 1, 2, 2, 2, 3]。我可以想象做以下事情。

A = [1, 2, 3, 1]
result = []
for i,n in enumerate(A):
    result += [i] * n

result 是我想要的输出。但正如您所看到的,该解决方案不是很优雅。如何做得更好?

【问题讨论】:

    标签: python list-comprehension


    【解决方案1】:

    您可以使用嵌套列表推导:

    lst = [1, 2, 3, 1]
    
    output = [i for i, x in enumerate(lst) for _ in range(x)]
    print(output) # [0, 1, 1, 2, 2, 2, 3]
    

    【讨论】:

      【解决方案2】:

      使用itertools 函数的一些方法,虽然我认为你的循环非常好,如果他们还没有的话,我可能已经写了 j1-lee。

      from itertools import chain, repeat, count, starmap
      
      result = [*chain(*map(repeat, count(), A))]
      result = list(chain.from_iterable(map(repeat, count(), A)))
      result = list(chain.from_iterable(starmap(repeat, enumerate(A))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        • 2017-01-02
        • 2021-06-25
        • 1970-01-01
        • 1970-01-01
        • 2022-10-07
        • 2019-09-08
        相关资源
        最近更新 更多