Check if element exists in tuple of tuples

前端 未结 2 847
刺人心
刺人心 2020-12-03 01:14

I have a list of tuples that look like :

CODES = (
    (\'apple\', \'reddelicious\'),
    (\'caramel\', \'sweetsticky\'),
    (\'banana\', \'yellowfruit\'),
         


        
2条回答
  •  被撕碎了的回忆
    2020-12-03 01:50

    You can use itertools.chain():

    Using it with in will result in short-circuiting, similar to 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 comparisons you can check my other answer.

提交回复
热议问题