Find an element in a list of tuples

前端 未结 10 829
感动是毒
感动是毒 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:30

    Or takewhile, ( addition to this, example of more values is shown ):

    >>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
    >>> import itertools
    >>> list(itertools.takewhile(lambda x: x[0]==1,a))
    [(1, 2), (1, 4)]
    >>> 
    

    if unsorted, like:

    >>> a= [(1,2),(3,5),(1,4),(5,7)]
    >>> import itertools
    >>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
    [(1, 2), (1, 4)]
    >>> 
    

提交回复
热议问题