python - 查找列表的索引,该列表是更大列表的一部分
问题描述
我有各种复杂的列表,例如
lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]
我需要在顶部列表中找到项目的位置。我的输出将是 item, index 的第一个列表:
0 3
1 2
2 2
3 0
4 1
5 2
所以 5,1,2 在位置 3。
在另一个列表中:
0 1
1 2
2 3
3 0
4 0
5 2
子列表的数量可以变化,每个子列表都可以有子列表。
为了简化,我搜索了任何带有“,”的列表,并将其平铺成 1 个子列表。
我可以有一个单独的元素和列表的列表,但我无法获得索引。我还尝试将单个元素转换为单个项目列表并附加它,但我仍然无法获得子列表的索引。
解决方案
你可以使用这样的函数:
def find_index(val, lst):
for i, x in enumerate(lst):
if val == x:
return i
elif type(x) is list: # or type(x) not in {float, int}
try:
find_index(val, x)
# matched without error
return i
except ValueError:
# not in list
pass
# not found
raise ValueError('{} is not in the list'.format(val))
这使用该enumerate
函数从列表中获取项目及其索引。然后,如果可能,它会直接针对所需值测试每个项目。如果该项目是一个列表,它会递归地检查它。
测试:
lst = [[3, 4], 0, [1, [5]], 2]
for x in range(6):
print x, find_index(x, lst)
# 0 1
# 1 2
# 2 3
# 3 0
# 4 0
# 5 2
如果您希望能够使用任何类型的可迭代(不仅仅是list
s),您可以尝试这个更通用的代码,但它更难遵循:
def find_index(val, values):
try:
# Search list of items
for i, x in enumerate(values):
try:
find_index(val, x) # any error?
return i # succeeded
except ValueError:
pass
except TypeError:
# not a list, just an item
if values == val:
return 0 # found
# not found
raise ValueError('{} is not in the list'.format(val))
推荐阅读
- php - 将创建奇怪的 PHP 输出
- android - Android 10 以下没有互联网的情况下,Android 会自动与 WiFi 断开连接
- chart.js - 我们可以在图表栏的顶部有数值吗?
- spring - Spring Sleuth 通过模式或“mvc.controller.class”忽略“get /**”
- python - PyTorch 反卷积层输入维度与线性层不匹配
- amazon-web-services - AWS CloudFront + API Gateway - 检测部署何时完成
- swift - 如何正确使用 MVVM 和 SwiftUI?
- wordpress - 使用 LAMP 在 MAC 上配置 Apache 虚拟主机
- python - 如何阻止熊猫 value_counts 计算标题行
- python - Python密码验证