Filter a list of tuples based on condition

前端 未结 3 2054
失恋的感觉
失恋的感觉 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: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)
    

提交回复
热议问题