Python 如何在嵌套列表中搜索列表的编号,并在其他嵌套列表中获取其索引?
我宣布:Python 如何在嵌套列表中搜索列表的编号,并在其他嵌套列表中获取其索引?,python,python-3.x,list,for-loop,list-comprehension,Python,Python 3.x,List,For Loop,List Comprehension,我宣布: 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 我想做的是,例如,如果numsToSearch[0]在anyN
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
我想做的是,例如,如果numsToSearch[0]
在anyNums[rtsian[0]]]
中进行搜索(换句话说,这将是因为,我正在查找anyNums
的0行中的数字1的索引)如果是True
则在名为index
的其他嵌套列表中获取其索引,如果不是True,则只需在嵌套列表中追加“数字不在列表中”
,然后再次搜索numtosearch[1]
是否在anyNums[rtsian[1]
中,如果是True
,在嵌套列表中获取其索引索引
。如果是False
,则只需在嵌套列表中添加“号码不在列表中”
这一过程对其他人重复。因此,在最后一次打印索引时,
会显示在控制台[[0],[1,2],“数字不在列表中”]
我刚刚试过这个:
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)
这样我就得到了下一个错误indexer:list index超出范围
,因为我知道for循环和列表的正确索引丢失了
我希望有人能帮助我,谢谢 您的代码中有很多问题。一些主要的是
:但您刚刚创建了索引列表,从未创建过索引[i]子列表。要解决此问题,您可以添加索引[i].append()
,就像外部索引。追加([])
循环中的第一行一样for
:我认为这里您希望迭代对于范围内的j(len(anyNums[i]))
rtsian提供的行,因此对于范围内的j(len(anyNums[rtsian[i]]),更好的是
。
索引器
解决上述两个问题后,仍然无法获得所需的输出,因此我在代码中做了一些更改:
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的直观代码,尽管它可能不是解决其查询的最佳代码。如果索引困扰您,请尝试在enumerate(一些列表)中输入i,v,而不是在range(len(…)中输入i)