首页 > 解决方案 > 如何在嵌套列表中搜索列表的编号并在其他嵌套列表中获取其索引?

问题描述

我宣布:

anyNums = [
    [1,8,4], 
    [3, 4, 5, 6], 
    [20, 47, 47], 
    [4, 5, 1]
]   #List for find the numbers

numsToSearch = [1, 47, 20]    #Numbers to search

rtsian = [0, 2, 3]    #Rows to search in any numbers

我想要做的是例如搜索 if numsToSearch[0]is in anyNums[rtsian[0]](换句话说,我正在寻找 0 行中数字 1 的索引anyNums),如果它True在其他嵌套列表中获取它的索引或索引命名indices如果它不正确,只需追加到嵌套列表中,"The number is not in the list"然后再次搜索是否numsToSearch[1]anyNums[rtsian[1]],如果是True,则在嵌套列表中获取其索引或索引indices。如果是False,那么只需追加到嵌套列表中"The number is not in the list"

对其他的重复这个过程。所以最后当我indices在控制台打印这个显示时[[0], [1,2], ["The number is not in the list"]]

我刚试过这个:

anyNums = [
    [1,8,4], 
    [3, 4, 5, 6], 
    [20, 47, 47], 
    [4, 5, 1]
]   #List for find the numbers

numsToSearch = [1, 47, 20]    #Numbers to search

rtsian = [0, 2, 3]    #Specially rows to search in any numbers

indices = []
    
for i in range(len(rtsian)):
    for j in range(len(anyNums[i])):
        if numsToSearch[i] in anyNums[rtsian[i]]:
            indices[i].append(
                anyNums[rtsian[i]].index(
                    anyNums[rtsian[i]][j]
                )
            )
        else:
            indices[i].append("The number is not in the list")
print(indices)

有了这个,我得到了下一个错误IndexError: list index out of range,因为我知道我迷失了 for 循环和列表的正确索引。

我希望有人可以帮助我,谢谢!

标签: pythonpython-3.xlistfor-looplist-comprehension

解决方案


您的代码中存在相当多的问题。一些主要的是

  • indixes[i].append():但是您只是创建了索引列表,而从未创建过索引 [i] 子列表。要解决此问题,您可以在外循环中添加indixes.append([])第一行。for

  • for j in range(len(anyNums[i])):我认为您想在这里迭代由提供的行,rtsian以便更好的行for j in range(len(anyNums[rtsian[i]]))

上面两个是生产的IndexError

解决上述两个问题后,您仍然无法获得所需的输出,因此我对代码进行了更多更改::

anyNums = [[1,8,4], 
           [3, 4, 5, 6], 
           [20, 47, 47], 
           [4, 5, 1]]       #List for find the numbers
numsToSearch = [1, 47, 20]  #Numbers to search

rtsian = [0, 2, 3]          #Specially rows to search in any numbers

indixes = []
    
for i in range(len(rtsian)):
    indixes.append([])
    found = False
    for j in range(len(anyNums[rtsian[i]])):
        if numsToSearch[i] == anyNums[rtsian[i]][j]:
            indixes[i].append(j)
            found = True
    if not found:
        indixes[i].append("The number is not in the list")
print(indixes)

输出:

[[0], [1, 2], ['The number is not in the list']]

注意:上面将是 OP 的直观代码,尽管它可能不是解决他的查询的最优化代码。


推荐阅读