简体   繁体   English

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

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

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)] 说我有[('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? 我想确定FIRST元素为A的元组。如何返回以下内容?

[('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: 你可以使用Python的filter函数,如下所示:

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

Giving: 赠送:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查元组列表是否具有元组的元组作为定义的字符串 - Check that list of tuples has tuple with 1st element as defined string 将元组列表转换为dataframe - 其中元组的第一个元素是列名 - Convert list of tuples to dataframe - where first element of tuple is column name 元组列表中元组的小写第一个元素 - Lowercase first element of tuple in list of tuples 访问元组列表中元组第一个元素的范围 - Accessing a range of the first element of a tuple in a list of tuples Python 2.7-检查单元素元组列表中二元素元组中的第一个元素 - Python 2.7 - Check if first element in two-element tuple in list of single-element tuples 将元组的第二个元素(在元组列表中)获取为字符串 - Getting second element of a tuple (in a list of tuples) as a string Python 程序检查指定元素是否出现在元组的元组中 - Python program to check if a specified element presents in a tuple of tuples 如何将元组列表写入到csv文件中,其中元组的第一个元素是字典? - How can I write a list of tuples to a csv file where the first element of the tuple is a dictionary? 用python中元组列表中元组的第一个元素索引元素的最快方法 - Fastest way to index an element by the first element of a tuple in a list of tuples in python 在列表中访问元组列表中元组的第一个元素 - python - Accessing first element of a tuple in a list of tuples, in a list - python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM