This question is similar to Check that list of tuples has tuple with 1st element as defined string but no one has properly answered the "wildcard" question.
Say I have [('A', 2), ('A', 1), ('B', 0.2)]
And I want to identify the tuples where the FIRST element is A. How do I return just the following?
[('A', 2), ('A', 1)]
Using a list comprehension:
>>> l = [('A', 2), ('A', 1), ('B', 0.2)]
>>> print([el for el in l if el[0] == 'A'])
[('A', 2), ('A', 1)]
Simple enough list comprehension:
>>> L = [('A', 2), ('A', 1), ('B', 0.2)]
>>> [(x,y) for (x,y) in L if x == 'A']
[('A', 2), ('A', 1)]
You could use Python's filter
function for this as follows:
l = [('A', 2), ('A', 1), ('B', 0.2)]
print filter(lambda x: x[0] == 'A', l)
Giving:
[('A', 2), ('A', 1)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.