【问题标题】:Nested List Operations By Index按索引的嵌套列表操作
【发布时间】:2019-12-20 21:27:17
【问题描述】:

我有一个嵌套列表,嵌套列表中的每个元素都是一组 4。我想对列表中的每个元素执行算术运算,但不确定如何访问它们。

my_nested_list = [[1, 0, 0, 3], [7, 2, 2, 3], [1, 3, 4, 3]]

for i in my_nested_list:
    for num in i:
        if num[0] == 7:      
            num[1] = num[1] * num[1]

如果嵌套列表的第一个数字 == 7,我如何将嵌套列表的第二个数字平方?我认为我上面的代码可以工作,但事实并非如此。有什么想法吗?

我期望的输出是 2 变成 4。

my_nested_list = [[1, 0, 0, 3], [7, 4, 2, 3], [1, 3, 4, 3]]

【问题讨论】:

  • my_listed_list 是整数列表的列表。你有for i in my_nested_list,所以i 是一个整数列表。你有for num in i,所以num 是一个整数。 num[0] 应该是什么?
  • 刚刚更新了我期待的输出。
  • @oppressionslayer 三个错误,一个用索引循环替换了外部循环,一个令人震惊的弹出+插入。学生的答案是唯一一个不错的。

标签: python loops nested-loops nested-lists


【解决方案1】:

您可以遍历嵌套列表中的列表,您可能只需要检查第一个元素而不是迭代内部列表。也许您可以尝试以下操作:

my_nested_list = [[1, 0, 0, 3], [7, 2, 2, 3], [1, 3, 4, 3]]

for num in my_nested_list:
    if num[0] == 7: # for each list only need to compare first element
        num[1] = num[1] * num[1]
print(my_nested_list)

输出:

[[1, 0, 0, 3], [7, 4, 2, 3], [1, 3, 4, 3]]

【讨论】:

    【解决方案2】:
    my_nested_list = [[1, 0, 0, 3], [7, 1, 2, 3], [1, 3, 4, 3]]
    
    for i in my_nested_list:
      for j in 3: # you have 3 lists
        if my_nested_list[j][i] == 1:
          my_nested_list[j][i+1]**2
    

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多