Why is a tuple of tuples of length 1 not actually a tuple unless I add a comma?

筅森魡賤 提交于 2020-06-23 08:16:14

问题


Given a tuple of tuples T:

(('a', 'b'))

and an individual tuple t1:

('a','b')

why does:

t1 in T

return False?

UPDATE: From Ipython:

In [22]: T = (('a','b'))

In [23]: t1 = ('a','b')

In [24]: t1 in T
Out[24]: False

And how then to check that a tuple is in another tuple?


回答1:


The problem is because T is not a tuple of tuples, it is just a tuple. The comma makes a tuple, not the parentheses. Should be:

>>> T = (('a','b'),)
>>> t1 = ('a', 'b')
>>> t1 in T
True

In fact, you can loose the outer parentheses:

>>> T = ('a','b'),
>>> t1 = 'a','b'
>>> type(T)
<type 'tuple'>
>>> type(T[0])
<type 'tuple'>
>>> type(t1)
<type 'tuple'>
>>> t1 in T
True

Although sometimes they are needed for precedence, if in doubt put them in. But remember, it is the comma that makes it a tuple.




回答2:


Doing this (('a', 'b')) does not make a tuple containing a tuple as you can see here:

>>> T = (('a','b'))
>>> T
('a', 'b')

To make a single element tuple you need to add a trialing comma:

>>> T = (('a','b'),)
>>> t1 in T
True
>>> T
(('a', 'b'),)

In fact the parenthesis aren't even a requirement as this will also create a tuple:

>>> t1 = 'a','b'
>>> t1
('a', 'b')
>>> 1,2,3,4,5,6
(1, 2, 3, 4, 5, 6)



回答3:


Check again. You likely have a bug somewhere else in your code. This check does work.

As for the update, you're not creating a nested tuple.

(('a', 'b')) == ('a', 'b')

If you need a one-element tuple, you need a trailing coma:

(('a', 'b'),)


来源:https://stackoverflow.com/questions/31293862/why-is-a-tuple-of-tuples-of-length-1-not-actually-a-tuple-unless-i-add-a-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!