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
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']
>>>
try :
In [4]: [x[1] for x in A if x[0] > 2]
Out[4]: ['K', 'J']
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)