首页 > 解决方案 > Find index element in a list of lists and strings

问题描述

I have a list containing strings and lists. Something like:

l = ['a', 'b', ['c', 'd'], 'e']

I need to find the index of an element I'm looking for in this nested list. For instance, if I need to find c, the function should return 2, and if I'm looking for d, it should return 2 too. Consider that I have to do this for a large number of elements. Before I was simply using

idx = list.index(element)

but this does not work anymore, because of the nested lists. I cannot simply flatten the list, as I then shall use the index in another list with the same shape as this one.

Any suggestion?

标签: pythonindexing

解决方案


这是一种方法,迭代列表。

前任:

l = ['a', 'b', ['c', 'd'], 'e']
toFind = "c"
toFind1 = "d"

for i, v in enumerate(l):
    if isinstance(v, list):
        if toFind1 in v:
            print(i)
    else:
        if toFind1 == v:
            print(i)

推荐阅读