【问题标题】:How to replace all list of list items with the index value of that list如何用该列表的索引值替换所有列表项列表
【发布时间】:2022-11-27 00:00:22
【问题描述】:

我正在尝试用该特定列表的索引值替换列表列表中的项目。我可以用 for 循环来做,但我想知道是否有更快的方法来做到这一点。

这样下面的列表

example = [[1,2,3], [4,5,6], [7,8,9]]

变成:

solution = [[0,0,0], [1,1,1], [2,2,2]]

【问题讨论】:

    标签: python list replace


    【解决方案1】:

    列表理解通常比循环更快

    这是一个列表理解的解决方案

    example = [[1,2,3],[4,5,6],[7,8,9]]
    solution = [[x for _ in range(len(example[x]))] for x in range(len(example))]
    print(solution)
    
    Output
    [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
    

    【讨论】:

    • 为什么不用enumerate()?您可以使用乘法生成一定长度的列表。
    【解决方案2】:

    你使用 for 循环的方式应该可行,但如果你想要另一种简短版本的方式,那么你可以这样做,

    example = [[1,2,3],[4,5,6],[7,8,9]]
    result = [[i, i, i] for i,_ in enumerate(example)]
    print(result)
    

    【讨论】:

      【解决方案3】:

      这是map操作的解决方案:

      res = list(map(lambda i : [i] * len(example[i]),
                  range(len(example))
              ))
      print(res)
      

      它比理解方法更冗长,但来自其他语言我更喜欢它 - 我发现 map 更明确且更容易理解,因为它是由高阶函数的公共组件构建的,而不是拥有自己的组件句法。

      【讨论】:

        猜你喜欢
        • 2021-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-19
        • 2023-03-26
        • 2017-03-31
        • 1970-01-01
        • 2022-11-10
        相关资源
        最近更新 更多