简体   繁体   中英

'in' operator does not work with tuples and sets in python

If I have two identical tuples:

>>> e = ('a', 1)
>>> c = ('a', 1)
>>> e == c
True
>>> hash(e)
9135824190991152417
>>> hash(c)
9135824190991152417

but to my surprise:

>>> se = set(c)
>>> e in se
False

how can I use a set to check if a tuple is in it?

As you can see, e is NOT an element of se , so in returns false

se = {'a', 1}
e = ('a', 1)

As set() takes an iterable, and uses its values to populate its structure, you can't pass your tuple like this, use the {} syntax, or give a list (or tuple) that containes your tuple

# {('a', 1)}
se = {c} 
se = set((c,)) 
se = set([c])

In your example se = {'a', 1} not {('a',1)} and hence you get false. To create a set of tuples as which I think you want, use either set([c,]) or {c}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM