简体   繁体   中英

how to test if an integer is in a sub-list in a list

I'd like to test if 3 is the first number of the element (an integer or the first of a sub-list) like this :

lst=[2, [3,6], [4,1,7]]
3 in lst

The result should be True because 3 is the first element of [3,6].

Btw: my dataset won't make my list like [3, [3,7]] (alone and in a sublist)

You can do this with a pretty simple recursive function like:

l =[2, [3,6], [4,1,7]]

def inList(l, n):
    if isinstance(l, list):
        return l[0] == n or any(inList(member, n) for member in l[1:])
    else:
        return False

inList(l, 3) # True
inList(l, 9) # False
inList(l, 2) # True

This has the advantage of digging into deeply nested lists too:

l =[2, [3,6], [4,1,[9,[5]], 7]]
inList(l, 5) # True

Assuming no sub-sub-lists:

l=[2, [3,6], [4,1,7]]
first_elements = [i[0] if isinstance(i, list) else i for i in l]  # [2, 3, 4]
print(3 in first_elements)

Output:

True

You can iterate over the List, and check if sub-elements sub is a list or an integer, and return your desired result :

L = [2, [3,6], [4,1,7]]
num = 2
res = False
for sub in L:
    if isinstance(sub, list):
        if num in sub:
            res = True
            break
    else:
        if num == sub:
            res = True

print(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM