1、什么是列表
列表是由一系列按特定顺序排列的元素,元素之间可以没有任何关系;可以创建空列表,也可以将任何东西添加进列表。
列表用 [ ] 表示:
cars = ['golf', 'magotan', 'sagitar', 'jetta']
2、列表序列是从0开始
1 cars = ['golf', 'magotan', 'sagitar', 'jetta'] 2 print(cars[0]) 3 golf 4 print(cars[2]) 5 sagitar
3、首字母大写
1 cars = ['golf', 'magotan', 'sagitar', 'jetta'] 2 print(cars[0].title()) 3 Golf
4、遍历列表的方法
⑴
cars = ['golf', 'magotan', 'sagitar', 'jetta']
for i in cars:
print(i)
⑵
cars = ['golf', 'magotan', 'sagitar', 'jetta']
length = len(cars)
i = 0
while i < length:
print(cars[i])
i+=1
5、append
添加元素,整体添加
cars = ['golf', 'magotan', 'sagitar', 'jetta']
tem = ['bora', 't-roc']
cars.append(tem)
print(cars) # ['golf', 'magotan', 'sagitar', 'jetta', ['bora', 't-roc']]
6、extend
添加元素,将另一个集合中的元素逐一添加到列表中
cars = ['golf', 'magotan', 'sagitar', 'jetta']
tem = ['bora', 't-roc']
cars.extend(tem)
print(cars) # ['golf', 'magotan', 'sagitar', 'jetta', 'bora', 't-roc']
7、insert
在指定index索引位置前插入元素
cars = ['golf', 'magotan', 'sagitar', 'jetta']
cars.insert(2, 'tayron')
print(cars) #['golf', 'magotan', 'tayron', 'sagitar', 'jetta']
8、修改元素
cars = ['golf', 'magotan', 'sagitar', 'jetta']
cars[0] = 'tayron'
print(cars) # ['tayron', 'magotan', 'sagitar', 'jetta']
9、in(包含结果为true,不包含结果为false), not in(不包含结果为False,包含结果为True), index, count
cars = ['tayron', 'jetta', 'magotan', 'sagitar', 'jetta', 'bora', 't-roc']
love_car = 'tayron'
if love_car in cars:
print('包含有')
# ------------------------
cars.index('jetta', 2, 4)
# jetta 在1和4的位置,所以报错
'''
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
cars.index('jetta', 2, 4)
ValueError: 'jetta' is not in list
'''
cars.count('bora')
# 5
10、删除元素del, pop, remove
del:根据下标进行删除
pop:删除最后一个元素
remove:根据元素的值进行删除
11、排序sort, reverse
sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
reverse方法是将list逆置。