Python 元组(Tuples)与列表(List)

       Python中Tuples和List都是Sequence数据类型的一种,不同的Tuples的值不能修改,但是我们可以通过拼凑来得到新的元组。 

        Tuples有个特别的就是在初始化含有0个或者1个元素的元组时,初始化0个元素的元组使用一对空括号(Tup=())。初始化含有一个元素的元组时按照逻辑应该是这样的Tup=(“Hello”),但是其实不是这样的这样得到的Tup其实是一个字符串并不是一个元组。正确的方法应该是 Tup=(”Hello“,)。这可能是因为括号可能会被当做括号运算所以需要加一个逗号来分别。如下面的例子:

Tup1=()
print Tup1
()
Tup2=("Hello")
print Tup2
Hello   #从输出结果也可以看出它是一个字符串而不是元组因为没有用双括号

Tup3=("Hello",)
print Tup1 in Tup3
False   #空元组并不包含于所有的非空元组

print Tup2 in Tup3
True    #字符串存在于元组

print Tup3 in Tup1
False   

print Tup1 in Tup2 
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not tuple  # 进一步印证Tup2不是元组

print Tup3 in Tup1
False

print Tup3 in Tup2
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not tuple

 官方文档:A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.


猜你喜欢

转载自blog.csdn.net/weixin_39730950/article/details/79536047