检查元素是否存在于元组的元组中 [英] Check if element exists in tuple of tuples
问题描述
我有一个看起来像元组的列表:
I have a list of tuples that look like :
CODES = (
('apple', 'reddelicious'),
('caramel', 'sweetsticky'),
('banana', 'yellowfruit'),
)
检查该元组中是否存在值的最佳方法是什么?例如,我希望能够说:
What's the best way to check if a value exists in that tuple? For example I want to be able to say:
'apple' in CODES
并获得True
推荐答案
您正在寻找 any()
:
You are looking for any()
:
if any('apple' in code for code in CODES):
...
结合简单的生成器表达式,即可完成此任务.生成器表达式采用每个元组,如果包含'apple'
,则生成True
. any()
然后在它请求的第一项返回True
时返回True
(否则为False
).因此,这就是您想要的.它也读得很好-如果任何元组包含'apple'
,则.
Combined with a simple generator expression, this does the task. The generator expression takes each tuple and yields True
if it is contains 'apple'
. any()
then returns True
when the first item it requests returns True
(otherwise, False
). Hence this does what you want. It also reads nicely - if any of the tuples contain 'apple'
.
如果您要执行大量操作并且需要性能,那么可能值得对所有值进行一组设置以使您快速执行此操作:
If you are doing this a massive number of times and need performance, then it might be worth making a set of all of the values to allow you to do this very quickly:
cache = set(itertools.chain.from_iterable(CODES)))
自然,构造它会很慢并且会占用内存,因此,除非您需要大量的性能并进行大量的成员资格检查,否则这不是一个好主意.
Naturally, constructing this will be slow and use memory, so it wouldn't be a good idea unless you need a lot of performance and will be doing a lot of membership checks.
这篇关于检查元素是否存在于元组的元组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!