Loading

数据类型_元组

一、元组数据类型

“元组”数据类型几乎域列表数据类型一样。首先元组输入时用括号(),而不是方括号[]  

>>> eggs = ("hello",42,0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)

元组像字符串一样,是不可改变的,元组不可能让它们的值被修改,添加,删除

>>> eggs = ("hello",42,0.5)
>>> eggs[0]=98
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
  • 下标取值
  • 切片
  • 用于for循环
  • 用于len()
  • 用于in 和 not in 操作符
>>> eggs = ("hello",42,0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> for i in eggs:
...     print(i)
...
hello
42
0.5
>>> len(eggs)
3
>>> "hello" in eggs
True

如果元组中只有一个值,可以在括号内该值的后面跟上一个逗号

>>> type(("good morning",))
<class 'tuple'>
>>> type(("good morning"))
<class 'str'>

用list()和tuple()函数来转换类型

>>> tuple(["cat","dog",5])
('cat', 'dog', 5)
>>> list(["cat","dog",5])
['cat', 'dog', 5]
>>> list("hello")
['h', 'e', 'l', 'l', 'o']

 

posted @ 2023-04-16 00:13  solomon-zj  阅读(13)  评论(0)    收藏  举报