Python2学习笔记(3)

list

Python内置的一种数据类型列表,是一种有序的集合。可随时增加和删除元素。

  • list是一种有序的集合,写在中括号中。
>>> name
['a', 'b', 'c']
>>> grade = [12,34,10]
>>> grade
[12, 34, 10]
  • len()函数可以获得list的长度
>>> len(grade)
3
>>> a =[] #空的list,长度为0
>>> len(a)
0
  • 访问list中的元素可以用索引
>>> name[0]  #索引从0开始
'a'
>>> name[2]
'c'
>>> name[3] #下标越界,最后一个元素的索引是len(name)-1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> name[-1] #以负数作索引,可以从后边倒着访问list中的元素
'c'
>>> name[-3]
'a'
  • 插入元素【append,insert
>>> name.append('d') #使用 append 函数追加元素到list后边
>>> name
['a', 'b', 'c', 'd']
>>> name.insert(1,'A')#使用 intert 函数在指定索引处增加元素,其余元素向后移动
>>> name
['a', 'A', 'b', 'c', 'd']
  • 删除元素【pop,pop(i)
>>> name.pop() #使用 pop 函数删除末尾的元素
'd'
>>> name
['a', 'A', 'b', 'c']
>>> name.pop(0) #使用 pop(i) 函数删除指定位置的元素
'a'
>>> name
['A', 'b', 'c']
  • 替换元素(直接给指定位置赋新值)
>>> name
['A', 'b', 'c']
>>> name[2] = 'B'
>>> name
['A', 'b', 'B']
  • list 中可以存在不同的数据类型
>>> student_infortation = ['liming',18,True,[56,87,89,50]]
>>> student_infortation
['liming', 18, True, [56, 87, 89, 50]]
>>> student_infortation[3]
[56, 87, 89, 50]
>>> student_infortation[-1][1]#查看元素的元素
87

tuple

是一种有序列表叫元组,一旦初始化就不能修改

  • 用圆括号括起来表示元阻
>>> country = ('china','shannxi','beijing') 
>>> country
('china', 'shannxi', 'beijing')
>>> team = ('abc',16,True) #可以存在不同的数据类型
>>> team
('abc', 16, True)
>>> t = () #空的元组
>>> t
()
>>> len(t)
0

注意:元阻中只有一个元素的情况

>>> t = (3) #这种实际上是定义了数字3,因为圆括号又表示数学公式中的小括号,这里python规定按小括号进行计算
>>> t
3
>>> t = (3,) #python中定义一个元阻元素要在其后边加上逗号,且输出这一个元素也要在其后面加逗号,来消除歧义
>>> t
(3,)
>>> len(t)
1
  • tuple元素指向永远不变
>>> team
('abc', 16, True)
>>> team[1]    #查看元素,用索引
16
>>> team[1]=3  #元素不可更该
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> group = ('zhangsan',[23,45,67,89])
>>> group[1][2] = 66   #元组中list的元素更改。更改的实际上是list的元素的指向,但元组依旧指向该list没有发生改变
>>> group
('zhangsan', [23, 45, 66, 89])

猜你喜欢

转载自blog.csdn.net/jjt_zaj/article/details/51533113