Select value from list of tuples where condition

前端 未结 3 1762
旧时难觅i
旧时难觅i 2020-12-04 17:48

I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns) and I\'d like to make a query

select attribute1 from mylist where a         


        
相关标签:
3条回答
  • 2020-12-04 18:14

    One solution to this would be a list comprehension, with pattern matching inside your tuple:

    >>> mylist = [(25,7),(26,9),(55,10)]
    >>> [age for (age,person_id) in mylist if person_id == 10]
    [55]
    

    Another way would be using map and filter:

    >>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
    [55]
    
    0 讨论(0)
  • 2020-12-04 18:23

    If you have named tuples you can do this:

    results = [t.age for t in mylist if t.person_id == 10]
    

    Otherwise use indexes:

    results = [t[1] for t in mylist if t[0] == 10]
    

    Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

    0 讨论(0)
  • 2020-12-04 18:29

    Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

    filter(lambda t: t[0]==10, mylist)
    

    This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

    [age] = [t[1] for t in mylist if t[0]==10]
    

    But I would strongly recommend to use dictionaries or named tuples for this purpose.

    0 讨论(0)
提交回复
热议问题