Find an element in a list of tuples

前端 未结 10 826
感动是毒
感动是毒 2020-11-27 10:58

I have a list \'a\'

a= [(1,2),(1,4),(3,5),(5,7)]

I need to find all the tuples for a particular number. say for 1 it will be



        
10条回答
  •  长情又很酷
    2020-11-27 11:18

    There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary.

    For example,

    test = [("hi", 1), ("there", 2)]
    test = dict(test)
    print test["hi"] # prints 1
    

提交回复
热议问题