Filter a list of tuples based on condition

前端 未结 3 2029
失恋的感觉
失恋的感觉 2020-12-04 02:27

I have a list like this:

A=[(1,\'A\'),(2,\'H\'),(3,\'K\'),(4,\'J\')]

Each member of this list is like this: (number, string)

Now i

相关标签:
3条回答
  • 2020-12-04 03:01

    Use a list comprehension:

    [y for x,y in A if x>2]
    

    Demo:

    >>> A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
    >>> [y for x,y in A if x>2]
    ['K', 'J']
    >>> 
    
    0 讨论(0)
  • 2020-12-04 03:07

    try :

    In [4]: [x[1] for x in A if x[0] > 2]                                                                                                                                                                           
    Out[4]: ['K', 'J']
    
    0 讨论(0)
  • 2020-12-04 03:07

    You want to filter based on some condition, then display a representation of those items. There are a few ways to do this.

    List comprehension with filtering. This is usually considered idiomatic or “pythonic”

    B = [char for char, val in A if val > 2]
    

    Filter and map. This is lazy and useful if your list is very large and you don’t want to hold it all in memory at once.

    greater_than_2 = filter(lambda a: a[1] > 2, A)
    B = map(lambda a: a[0], greater_than_2)
    

    Or a loop and accumulator. This is good if you have side effects you want to do for each element.

    B = []
    for char, val in A:
        if val > 2:
            B.append(char)
    
    0 讨论(0)
提交回复
热议问题