(四)元组

2018-12-25  本文已影响0人  费云帆

1.一个赋值---所谓"元"组,就是"圆括号"

>>> a="abc",123,['name','age']
>>> a
('abc', 123, ['name', 'age'])
>>> type(a)
# 这就是元组
<class 'tuple'>
# 重新赋值是不行的,但可以转为列表后,再修改
>>> a[0]='def'
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a[0]='def'
TypeError: 'tuple' object does not support item assignment
>>> a.append('Jim Green')
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a.append('Jim Green')
AttributeError: 'tuple' object has no attribute 'append'
>>> 

2.单个元素的注意事项---末尾要加逗号

>>> a=(2)
>>> type(a)
<class 'int'>
>>> b=(2,)
>>> type(b)
<class 'tuple'>

3.列表和元组之间的转换---list()和tuple():

>>> tuple1=(1,2,3,4,5)
>>> list1=list(tuple1)
>>> list1
[1, 2, 3, 4, 5]
>>> tuple2=tuple(list1)
>>> tuple2
(1, 2, 3, 4, 5)
# 值一样,但是不是同一个对象
>>> tuple1 is tuple2
False
>>> id(tuple1)
44426432
>>> id(tuple2)
51184128
上一篇下一篇

猜你喜欢

热点阅读