检查元组的第一个元素由定义的字符串指定的列表

Check list of tuples where first element of tuple is specified by defined string

此问题与 Check that list of tuples has tuple with 1st element as defined string 类似,但没有人正确回答 "wildcard" 问题。

说我有 [('A', 2), ('A', 1), ('B', 0.2)]

我想识别第一个元素是 A 的元组。我如何 return 只是以下内容?

[('A', 2), ('A', 1)]

使用列表理解:

>>> l = [('A', 2), ('A', 1), ('B', 0.2)]
>>> print([el for el in l if el[0] == 'A'])
[('A', 2), ('A', 1)]

足够简单的列表理解:

>>> L = [('A', 2), ('A', 1), ('B', 0.2)]
>>> [(x,y) for (x,y) in L if x == 'A']
[('A', 2), ('A', 1)]

您可以使用 Python 的 filter 函数,如下所示:

l = [('A', 2), ('A', 1), ('B', 0.2)]
print filter(lambda x: x[0] == 'A', l)

给予:

[('A', 2), ('A', 1)]