python - 如何在嵌套列表中搜索列表的编号并在其他嵌套列表中获取其索引?
问题描述
我宣布:
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 循环和列表的正确索引。
我希望有人可以帮助我,谢谢!
解决方案
您的代码中存在相当多的问题。一些主要的是
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 的直观代码,尽管它可能不是解决他的查询的最优化代码。
推荐阅读
- solr - 无法在 Ubuntu 服务器上启动 solr
- ip - 为什么 ::1 不匹配 127.0.0.1?
- java - string 和 StringProperty 之间的类型不兼容
- mysql - mysql select 显示相同的 wp_agent_adds.id 不是唯一的
- android-studio - Android Studio 无法自动安装 apk,因为 AS 使用了错误的名称
- python - 在给定深度改变递归函数
- adobe-analytics - DTM:250ms的延迟链路激活真的有必要吗?
- twitter-bootstrap - 没有cdn的完整引导
- css - 如何用 flex 显示这个特定的模式?
- php - PayPal 支付失败,出现“得到 Http 响应代码 403”