简体   繁体   中英

Using python how to find elements in a list of lists based on a key that is an element of the inner list?

Suppose I have a list of lists or a list of tuples, whichever can solve my problem more efficiently. Eg:

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]

The task is to find an element in the main list based on a key that is any element of the inner list or tuple. Eg:

Using the list above:

find(student_tuples, 'A')

or

find(student_tuples, 15)

would both return

('john', 'A', 15)

I'm looking for an efficient method.

I would use filter() or a list comprehension.

def find_listcomp(students, value):
    return [student for student in students if student[1] == value or student[2] == value]

def find_filter(students, value):
    return filter(lambda s: s[1] == value or s[2] == value, students) 

To find the first match only, you can use

def find(list_of_tuples, value):
    return next(x for x in list_of_tuples if value in x)

This will raise StopIteration if no matching record is found. To raise a more appropriate exception, you can use

def find(list_of_tuples, value):
    try:
        return next(x for x in list_of_tuples if value in x)
    except StopIteration:
        raise ValueError("No matching record found")

You can use python's list comprehensions to select and filter:

def find(tuples, term):
    return [tuple for tuple in tuples if term in tuple]

This function will return a list of the tuples contain your search term. Here you go:

def find_in_tuples(tuples, term):
    matching_set = []
    for tuple in tuples:
        if term in tuple:
            matching_set.append(tuple)
    return matching_set

>>> find_in_tuples(student_tuples, 'A')
[('john', 'A', 15)]
>>> find_in_tuples(student_tuples, 'B')
[('jane', 'B', 12), ('dave', 'B', 10)]

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