Select value from list of tuples where condition

前端 未结 3 1853
旧时难觅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: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.

提交回复
热议问题