为什么除非我加逗号,否则长度为1的元组实际上不是元组? [英] Why is a tuple of tuples of length 1 not actually a tuple unless I add a comma?

查看:74
本文介绍了为什么除非我加逗号,否则长度为1的元组实际上不是元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个元组 T

(('a', 'b'))

和单个元组 t1

('a','b')

为什么这样做:

t1 in T

返回错误吗?

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?

推荐答案

问题是因为T不是元组的元组,它只是一个元组。逗号组成一个元组,而不是括号。应该是:

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

尽管有时需要使用它们作为优先级,如果有疑问,请放in。但是请记住,它是使它成为元组的逗号。

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

这篇关于为什么除非我加逗号,否则长度为1的元组实际上不是元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆