按索引的嵌套列表操作

问题描述 投票:-2回答:1

我有一个嵌套列表,嵌套列表中的每个元素都是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]]
python loops nested-loops nested-lists
1个回答
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
投票

您的问题是您有2个for循环,太多了。您遍历my_nested_list中的sub_list并检查第0个元素是否等于7,如果是,则弹出第一个元素并将第一个正方形的元素插入位置1

>>> my_nested_list = [[1, 0, 0, 3], [7, 4, 2, 3], [1, 3, 4, 3]]
>>> for i in my_nested_list:
...     if i[0] == 7:
...             s = i.pop(1)
...             i.insert(1, s*s)
...
>>> my_nested_list
[[1, 0, 0, 3], [7, 16, 2, 3], [1, 3, 4, 3]]

-3
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.