python是一种简单易学且功能壮大的编程说话,它具有白话化的酿成体例,深受大师喜爱。跟着人工智能的成长,python越来越受大师喜爱。在利用python编程的过程中我们总会碰到各类各样的问题,可是我们总会找到解决的方案的。例如下面的这个问题。
若何建立tuple这种数据类型。a=(1,2,3)就可以建立一个tuple数据了,list数据是a=[1,2,3].
界说空的tuple和只有一个元素的tuple。a=() a=(1,) 因为()既可以暗示建立tuple,也是一种运算符,所以,界说只有一个元素的tuple时必需在元素后面加一个‘,’来消弭歧义。
>>> b=()
>>> b
()
>>> b=(1)
>>> b
1
>>> b=(1,)
>>> b
(1,)
>>>
tuple数据中的元素也可所以一个tuple,也可所以字符串或者整数。
若何挪用tuple里的一个原始呢?和list中一样,用a[0] 而不是a(0),圆括号是挪用函数的方式。
>>> a=(1,2,3)
>>> a
(1, 2, 3)
>>> a(0)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a(0)
TypeError: 'tuple' object is not callable
>>> a[0]
1
>>> a[2]
3
tuple和list长短常相似的数据类型,不同是tuple建立了今后此中的元素不克不及点窜。
>>> a[0]=2
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a[0]=2
TypeError: 'tuple' object does not support item assignment
因为tuple不克不及点窜,所以它没有list的.append() .pop() .insert() 等属性。
>>> a.append(4)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a.append(4)
AttributeError: 'tuple' object has no attribute 'append'
>>> a.pop()
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
a.pop()
AttributeError: 'tuple' object has no attribute 'pop'
>>> a.insert(1,9)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.insert(1,9)
AttributeError: 'tuple' object has no attribute 'insert'
>>>
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!