如何在嵌套列表中搜索列表的编号并在其他嵌套列表中获取其索引?

问题描述

我声明:

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

numsToSearch = [1,20]    #Numbers to search

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

我想要做的是例如搜索 numsToSearch[0] 是否在 anyNums[rtsian[0]] 中(换句话说,我正在寻找 {{ 的 0 行中的数字 1 的索引) 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,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) ,因为我知道我丢失了 for 循环和列表的正确索引。

希望有人能帮帮我,谢谢!

解决方法

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

  • 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,1]]       #List for find the numbers
numsToSearch = [1,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 的直观代码,尽管它可能不是解决他的查询的最优化代码。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...