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

爱德华多·埃雷拉(Eduardo Herrera)

我宣布:

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]in anyNums[rtsian[0]](换句话说,就是我在anyNums的0行中寻找数字1的索引),如果为true,则获取其索引或其他嵌套索引命名为as的列表indixes,如果它不是true,则只需在嵌套列表中追加“数字不在列表中”,然后再次搜索numsToSearch [1]是否在anyNums [rtsian [1]]中,如果为true,则获取其索引或嵌套列表中的索引,indixes如果不正确,则只需在嵌套列表中追加“数字不在列表中”,其他过程相同。因此,最后,当我打印indexes此内容时,它将显示在控制台中[[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

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

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

里沙卜·库玛(Rishabh Kumar)

您的代码中有很多问题。一些主要的是

  • indixes[i].append():但是您只是创建了indixes列表,而从未创建过indixes [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的直观代码,尽管它可能不是解决他的查询的最优化的代码。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章