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

时间:2016-02-22 17:25:06

标签: python list tuples wildcard elements

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

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

我想识别FIRST元素为A的元组。如何返回以下内容?

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

3 个答案:

答案 0 :(得分:6)

使用列表理解:

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

答案 1 :(得分:3)

简单的列表理解:

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

答案 2 :(得分:2)

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

@Override
            public void onError(Status status) {
                Log.i(TAG, "An error occurred: " + status);
            }

,并提供:

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