20200928-Python学习笔记5

list

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

>>> classmate = ['w','1','yrw']
>>> classmate
['w', '1', 'yrw']
>>> len(classmate)
3
>>> classmate[0]
'w'
>>> classmate[2]
'yrw'
>>> classmate[-1]
'yrw'
>>> classmate[-3]
'w'
>>>

变量classmate就是一个list,可以用len()查看list元素个数,用索引来查看每个位置的元素,索引是从0开始的,输入0查看的是第一个元素,输入-1查看的是最后一个元素,输入的序号超出范围会报错。

在末尾添加元素用 append

>>> classmates = ['l','eee','opo']
>>> classmates.append('aaa')
>>> len(classmates)
4
>>> classmates
['l', 'eee', 'opo', 'aaa']
>>>

也可以插入到指定位置,用insert   ,  0是第一个元素,1是第二个元素

>>> classmates.insert(1,'yun')
>>> classmates
['l', 'yun', 'eee', 'opo', 'aaa']
>>>

删除list末尾的元素用pop()

>>> classmates.pop()
'aaa'
>>> classmates
['l', 'yun', 'eee', 'opo']
>>>

删除指定位置的元素  pop(i)  i=要删除元素的序号,索引位置

>>> classmates.pop(0)
'l'
>>> classmates
['yun', 'eee', 'opo']
>>>

替换某一元素,直接赋值给对应的索引位置

>>> classmates[0] = 'feng'
>>> classmates
['feng', 'eee', 'opo']
>>>

list中的元素类型也可以不同,也可以在list中假如list,要查看第二个list中的元素,先看list所在的位置的索引,再看元素在list中的索引

>>> oppo = ['op','po',3,9.99]
>>> oppo
['op', 'po', 3, 9.99]
>>> len(oppo)
4
>>> vivo = ['uu',['iu',66],'tyr']
>>> vivo
['uu', ['iu', 66], 'tyr']
>>> len(vivo)
3
>>> vivo[1][1]
66
>>>

空的list

>>> kong = []
>>> len(kong)
0
>>>

tuple:元组。也是一种有序列表,和list有相同之处,但是没有替换和删除

>>> oppo = ('aa','bb','cc')
>>> oppo
('aa', 'bb', 'cc')
>>>

在显示只有一个元素的tuple时,需要加上逗号,以免误解为数学意义上的括号

>>> shu = (1)
>>> shu
1
>>> shu = (3,)
>>> shu
(3,)
>>> len(shu)
1
>>> shu = ()
>>> shu
()
>>>

可替换的list,a是一个tuple元组,其中有一个list列表。tuple是无法替换的,但是其中的list是可替换的

>>> a = ('a','b',['c','d'])
>>> a[2][0] = 'e'
>>> a[2][1] = 'f'
>>> a
('a', 'b', ['e', 'f'])
>>>

  

原文地址:https://www.cnblogs.com/lookmefly/p/13745353.html