Find an element in a list of tuples

前端 未结 10 762
感动是毒
感动是毒 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
    
    0 讨论(0)
  • 2020-11-27 11:23

    if you want to search tuple for any number which is present in tuple then you can use

    a= [(1,2),(1,4),(3,5),(5,7)]
    i=1
    result=[]
    for j in a:
        if i in j:
            result.append(j)
    
    print(result)
    

    You can also use if i==j[0] or i==j[index] if you want to search a number in particular index

    0 讨论(0)
  • 2020-11-27 11:24
    [tup for tup in a if tup[0] == 1]
    
    0 讨论(0)
  • 2020-11-27 11:24

    Using filter function:

    >>> def get_values(iterables, key_to_find):
    return list(filter(lambda x:key_to_find in x, iterables)) >>> a = [(1,2),(1,4),(3,5),(5,7)] >>> get_values(a, 1) >>> [(1, 2), (1, 4)]
    0 讨论(0)
  • 2020-11-27 11:25
    for item in a:
       if 1 in item:
           print item
    
    0 讨论(0)
  • 2020-11-27 11:25

    The filter function can also provide an interesting solution:

    result = list(filter(lambda x: x.count(1) > 0, a))
    

    which searches the tuples in the list a for any occurrences of 1. If the search is limited to the first element, the solution can be modified into:

    result = list(filter(lambda x: x[0] == 1, a))
    
    0 讨论(0)
提交回复
热议问题