【问题标题】:How to process every nth element in each of this list of lists?如何处理每个列表列表中的每个第 n 个元素?
【发布时间】:2022-01-25 03:39:11
【问题描述】:

我有一个看起来像这样的列表;

list_of_lists = 
[
 [1640, 4, 0.173, 0.171, 0.172, 472], 
 [1640, 5, 0.173, 0.171, 0.173, 259], 
 [1640, 6, 0.175, 0.173, 0.173, 180], 
]

我想处理此列表列表中每个列表的第二个元素,以便将其替换为通过向其添加 1 创建的 2 个元素。它看起来像这样;

new_list_of_lists = 
[
 [1640, 5, 5, 0.173, 0.171, 0.172, 472], 
 [1640, 6, 6, 0.173, 0.171, 0.173, 259], 
 [1640, 7, 7, 0.175, 0.173, 0.173, 180], 
]

如何使用 python 3.9 做到这一点?谢谢。

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    您可以使用列表推导:

    list_of_lists = 
    [
     [1640, 4, 0.173, 0.171, 0.172, 472], 
     [1640, 5, 0.173, 0.171, 0.173, 259], 
     [1640, 6, 0.175, 0.173, 0.173, 180], 
    ]
    
    output = [[x[0], x[1] + 1, x[1] + 1, x[2], x[3], x[4], x[5]] for x in list_of_lists]
    print(output)
    

    打印出来:

    [
        [1640, 5, 5, 0.173, 0.171, 0.172, 472],
        [1640, 6, 6, 0.173, 0.171, 0.173, 259],
        [1640, 7, 7, 0.175, 0.173, 0.173, 180]
    ]
    

    【讨论】:

      【解决方案2】:

      我建议使用列表“切片”将第二个元素(切片 [1:2])替换为 2 元素列表:

      for list in list_of_lists:
          list[1:2] = [list[1] + 1] * 2
      

      【讨论】:

        【解决方案3】:

        第一种方法:单独更新每个元素

        list_of_lists[0][1] += 1
        list_of_lists[1][1] += 1
        list_of_lists[2][1] += 1
        

        第二种方法:更新所有元素

        for num in range(len(list_of_lists)):
        list_of_lists[num][1] += 1
        

        【讨论】:

          【解决方案4】:

          您可以使用列表推导式和变量来告诉它应该处理哪个索引:

          list_of_lists = [
           [1640, 4, 0.173, 0.171, 0.172, 472], 
           [1640, 5, 0.173, 0.171, 0.173, 259], 
           [1640, 6, 0.175, 0.173, 0.173, 180], 
          ]
          
          i = 1
          new_list_of_lists = [a[:i]+[a[i]+1]*2+a[i+1:] for a in list_of_lists]
          
          print(new_list_of_lists)
          [[1640, 5, 5, 0.173, 0.171, 0.172, 472], 
           [1640, 6, 6, 0.173, 0.171, 0.173, 259], 
           [1640, 7, 7, 0.175, 0.173, 0.173, 180]]
          

          【讨论】:

            猜你喜欢
            • 2020-01-10
            • 1970-01-01
            • 1970-01-01
            • 2013-05-24
            • 2020-12-08
            • 2015-01-12
            • 2021-02-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多