定义一个list使用[]
定义一个空列表 [] 或者 list()
列表中每个元素之间用逗号隔开
a_list = ['aa', 'bb', 'cc']
print(a_list)
# <class 'list'>
print(type(a_list))
list列表可以存储不同类型的元素
a_list = ['aa', 'bb', 'cc']
print(a_list)
# <class 'list'>
print(type(a_list))
b_list = list()
c_list = []
# list可以存储不同类型的元素
b_list = [True, False, "aa", 11, 3.14]
print(b_list)
list列表支持嵌套
b_list = [[1, 2, 3], [True, False], ['a', 'b', 'c']]
print(b_list)
list列表是有序的,可以根据下标取出元素,下标为负值反向取出元素
从前向后从0开始,每次+1,从后向前-1开始,每次-1
通过下标取数据,一定不能超出范围,否则会报错
a_list = ['aa', 'bb', 'cc']
# 正向取出元素
# aa
print(a_list[0])
# bb
print(a_list[1])
# 反向取出元素
# cc
print(a_list[-1])
# bb
print(a_list[-2])
取出嵌套列表中的元素
b_list = [[1, 2, 3], [True, False], ['a', 'b', 'c']]
# True
print(b_list[1][0])
# b
print(b_list[2][1])
方法
函数def定义在class类的成员,那么函数就被称为方法
# 函数
def add(x, y):
return x + y
# 5
print(add(1, 4))
# 类
class Student:
# 方法
def sum(self, x, y):
return x + y
stu1 = Student()
val = stu1.sum(4, 5)
# 9
print(val)
list本身就是一个类,里面定义了很多方法可供使用
index方法,获取元素在list中的下标索引位置
a_list = ['aa', 'bb', 'cc']
# index方法返回元素在list中的小标,如果找不到该元素报错
# 1
print(a_list.index('bb'))
# ValueError: 'b' is not in list
print(a_list.index('b'))
修改特定下标索引的值
a_list = ['aa', 'bb', 'cc']
# ['aa', 'bb', 'cc']
print(a_list)
# 通过元素下标修改,特定位置上的值
a_list[1] = 'tt'
# ['aa', 'tt', 'cc']
print(a_list)
insert方法,给list指定位置插入一个元素
a_list = ['aa', 'bb', 'cc']
# 在指定下标位置插入特定元素
# ['aa', 'bb', 'cc']
print(a_list)
a_list.insert(0, 'xx')
# ['xx', 'aa', 'bb', 'cc']
print(a_list)
append方法,给list的尾部追加元素
a_list = ['aa', 'bb', 'cc']
# ['aa', 'bb', 'cc']
print(a_list)
# 给list的尾部追加元素
a_list.append("xx")
# ['aa', 'bb', 'cc', 'xx']
print(a_list)
extend方法,给list的尾部追加另一个list
a_list = ['aa', 'bb', 'cc']
b_list = ["1", '2', '3']
a_list.extend(b_list)
# ['aa', 'bb', 'cc', '1', '2', '3']
print(a_list)
del方法删除元素,pop方法删除元素
a_list = ['aa', 'bb', 'cc']
del a_list[2]
# cc
print(a_list)
a_list = ['aa', 'bb', 'cc']
ele = a_list.pop(2)
# cc
print(ele)
取出最后一个元素
a_list = ['aa', 'bb', 'cc']
# cc
print(a_list[-1])
remove方法,通过值匹配第一个元素并进行删除
a_list = ['aa', 'bb', 'aa', 'cc']
a_list.remove('aa')
# ['bb', 'aa', 'cc']
print(a_list)
clear方法,清空整个列表
a_list = ['aa', 'bb', 'aa', 'cc']
# 清空整个列表
a_list.clear()
# []
print(a_list)
count方法,统计集合中元素的个数
a_list = ['aa', 'bb', 'aa', 'cc']
num = a_list.count('aa')
# 2
print(num)
len函数用来获取集合list的大小
a_list = ['aa', 'bb', 'aa', 'cc']
# 4
print(len(a_list))
while方式迭代list集合
def list_iterator():
"""
while循环迭代输出集合list中的元素
:return:
"""
a_list = [21, 25, 21, 23, 22, 20]
i = 0
while i < len(a_list):
ele = a_list[i]
print(ele)
i += 1
list_iterator()
for循环方式迭代list集合
def list_iterator():
"""
for循环迭代输出集合list中的元素
:return:
"""
a_list = [21, 25, 21, 23, 22, 20]
for ele in a_list:
print(ele)
list_iterator()
a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b_list = []
for ele in a_list:
if ele % 2 == 0:
b_list.append(ele)
print(b_list)
c_list = []
count = 0
while count < len(a_list):
ele = a_list[count]
if ele % 2 == 0:
c_list.append(ele)
count += 1
print(c_list)