【问题标题】:How to add the 3rd element of sub-list together in a 2 dimensional list如何将子列表的第三个元素添加到二维列表中
【发布时间】:2020-06-24 10:54:16
【问题描述】:

我正在尝试将每个子列表的第三个元素添加到我的二维列表中。这个我试过了。

total_order = [['Steve', 45, 6],['Miranda', 56, 3],['Alice', 34, 8]]
total_cost = 0
for i in total_order:
    total_cost += total_order[i][2]
    i += 1

我收到此错误:

TypeError: list indices must be integers or slices, not list

【问题讨论】:

    标签: python list for-loop multidimensional-array


    【解决方案1】:

    循环遍历一个列表不会给你一个列表的索引,而是实际的列表本身。

    我将您的 i 重命名为 order

    total_order = [['Steve', 45, 6], ['Miranda', 56, 3], ['Alice', 34, 8]]
    total_cost = 0
    for order in total_order:
        total_cost += order[2]
    

    但我建议您查看“生成器表达式”并使用内置的 sum 函数:

    total_order = [['Steve', 45, 6], ['Miranda', 56, 3], ['Alice', 34, 8]]
    total_cost = sum(order[2] for order in total_order)
    

    【讨论】:

      【解决方案2】:

      问题是在你的情况下不是数字而是一个列表。把 print(i) 放在那里,你会看到。

      ['Steve', 45, 6]
      ['Miranda', 56, 3]
      ['Alice', 34, 8]
      

      你应该有:

      total_cost += i[2]
      

      【讨论】:

        【解决方案3】:

        total_order 是一个列表列表,当您以您的方式迭代该对象时,您将获得一个列表对象 - 因此出现错误。 您可以使用enumerate 或更简单的方法对其进行迭代:

        total_cost = sum([item[2] for item in total_order])
        

        输出将是:

        17
        

        如果您不了解列表推导式,那么:

        for i in range(len(total_order)):
            total_cost += total_order[i][2]
        

        会输出相同的。

        【讨论】:

        • 非常感谢,没想到这么简单。现在说得通了:)
        【解决方案4】:

        您可以尝试添加i的第二项

        total_order = [['Steve', 45, 6],['Miranda', 56, 3],['Alice', 34, 8]]
        total_cost = 0
        for i in total_order:
            total_cost += i[2]
        print(total_cost)
        

        或使用 enumarte 按索引进行迭代

        for i, _ in enumerate(total_order):
            total_cost += total_order[i][2]
        

        输出

        17
        

        【讨论】:

          【解决方案5】:

          使用 Python 列表的索引方法:

          total_order = [['Steve', 45, 6],
                         ['Miranda', 56, 3],
                         ['Alice', 34, 8]
                         ]
          total_cost = 0
          
          for i in total_order:
              total_cost += total_order[total_order.index(i)][2]
          
          print(total_cost)
          

          给予:

          17
          

          【讨论】:

            猜你喜欢
            • 2021-10-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-05
            • 2021-08-06
            相关资源
            最近更新 更多