countries = ("中国","美国","英国")
如果元组内只有一个值,则必须加一个逗号,否则()就只是包含的意思而非定义元组
countries = ("中国",) # 本质:countries = tuple("中国")
但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型
tuple()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到元组中
>>> tuple(‘wdad‘) # 结果:(‘w‘, ‘d‘, ‘a‘, ‘d‘)
>>> tuple([1,2,3]) # 结果:(1, 2, 3)
>>> tuple({"name":"jason","age":18}) # 结果:(‘name‘, ‘age‘)
>>> tuple((1,2,3)) # 结果:(1, 2, 3)
>>> tuple({1,2,3,4}) # 结果:(1, 2, 3, 4)
tuple1 = (1, ‘hhaha‘, 15000.00, 11, 22, 33)
>>> tuple1[0]
1
>>> tuple1[-2]
22
>>> tuple1[0] = ‘hehe‘ # 报错:TypeError:
>>> tuple1[0:6:2]
(1, 15000.0, 22)
>>> len(tuple1)
6
>>> ‘hhaha‘ in tuple1
True
>>> ‘hhaha‘ not in tuple1
False
>>> for line in tuple1:
... print(line)
1
hhaha
15000.0
11
22
33
原文:https://www.cnblogs.com/Psc-mmf/p/13904733.html