Python 检查元素是否存在于元组的元组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15124833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if element exists in tuple of tuples
提问by 9-bits
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
and get True
并得到真实
采纳答案by Gareth Latty
You are looking for any():
您正在寻找any():
if any('apple' in code for code in CODES):
...
Combined with a simple generator expression, this does the task. The generator expression takes each tuple and yields Trueif it is contains 'apple'. any()then returns Truewhen 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'.
结合一个简单的生成器表达式,这就完成了任务。生成器表达式接受每个元组并True在它包含时产生'apple'。any()然后True在它请求的第一个项目返回时返回True(否则,False)。因此,这可以满足您的需求。它也很好读 -如果任何元组包含'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.
自然,构建它会很慢并且会占用内存,因此除非您需要大量性能并且将进行大量成员资格检查,否则这不是一个好主意。
回答by Ashwini Chaudhary
You can use itertools.chain():
您可以使用itertools.chain():
Using it with inwill result in short-circuiting, similar to any().
使用它in会导致短路,类似于any()。
In [30]: CODES = (
....: ('apple', 'reddelicious'),
....: ('caramel', 'sweetsticky'),
....: ('banana', 'yellowfruit'),
....: )
In [31]: from itertools import chain
In [32]: 'apple' in chain(*CODES)
Out[32]: True
In [33]: 'foo' in chain(*CODES)
Out[33]: False
For performance comparisonsyou can check my other answer.
对于性能比较,您可以查看我的其他答案。

