首页 > 解决方案 > 查找列表的索引,该列表是更大列表的一部分

问题描述

我有各种复杂的列表,例如

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 个子列表。

我可以有一个单独的元素和列表的列表,但我无法获得索引。我还尝试将单个元素转换为单个项目列表并附加它,但我仍然无法获得子列表的索引。

标签: pythonpython-2.7

解决方案


你可以使用这样的函数:

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

如果您希望能够使用任何类型的可迭代(不仅仅是lists),您可以尝试这个更通用的代码,但它更难遵循:

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))

推荐阅读