1. 程式人生 > >python小白之路(特性語法三之列表)

python小白之路(特性語法三之列表)

object 存在 根據 指定 zha 下標 end mov set

列表
一、列表的格式:變量為studentlist = [‘zhangsan’,‘male‘,29],元素可以是不同數據類型的。
二、打印列表:打印學生姓名print(studentlist[0])
三、列表的循環遍歷
1、for student in studentlist:
print(studentlist)
2、i = 0
length = len(students)
while i < length:
print(studentslist[i])
i += 1
四、列表的增、刪、改、排序
1、添加元素:append、extend、insert
append:通過append可以向列表尾追加元素。
extend:通過extend可以將另一個集合中元素逐一添加到表中。
insert:insert(index.object)在指定位置index前插入元素object。
2、修改元素
修改元素的時候,要通過下標來確定要修改的是哪個元素,然後才能進行修改。
3、查找元素:in、not in、index、count
查找就是看看看指定的元素是否存在。
in:存在返回True,否則返回False。
not in:與in相反。
index:A.index(‘a’,1,4)查找索引,不存在會報異常。
count:A.count(‘a’)統計個數。
4、刪除元素:del、pop、remove
del:根據下標進行刪除 del studentlist[0]。
pop:刪除最後一個元素 studentlist.pop()。
remove:根據元素的值進行刪除 studentlist.remove(‘name‘)
5、排序:sort、reverse
sort:將list按特定順序重新排列,默認為由小到大,參數reverseTrue可改為倒序,由大到小。
studentlist.reverse() studentslist.sort(reverse=True)
五、列表嵌套
一個列表中的元素又是一個列表。

python小白之路(特性語法三之列表)