1、创建列表:
# 创建列表的方式一:字面量语法
list1 = ['red', 'green', 'blue']
print(list1) # 输出['red', 'green', 'blue']
# 创建列表的方式二:构造器语法
list2 = list(range(1, 10))
print(list2) # 输出[1, 2, 3, 4, 5, 6, 7, 8, 9]
# 创建列表的方式三:生成式(推导式)语法
list3 = [i ** 2 for i in range(1, 10)]
print(list3) # 输出[1, 4, 9, 16, 25, 36, 49, 64, 81]
2、获取列表元素的个数(案例使用1定义列表):
# 获取列表元素的个数 ---> len()
print(len(list1)) # 3
print(len(list2)) # 9
print(len(list3)) # 9
3、遍历# (案例使用1定义列表):
# 遍历列表中的元素
for i in range(len(list1)):
print(list1[i])
'''
red
green
blue
'''
for x in list1: # 只能获取数据,不能修改也获取不了下标
print(x)
'''
red
green
blue
'''
for i, x in enumerate(list1): # 这种遍历最高效,即可以获取下标,也可以获取值
print(i, x)
'''
0 red
1 green
2 blue
'''
4、重复运算:
list4 = [1, 5, 6] * 5
print(list4) # [1, 5, 6, 1, 5, 6, 1, 5, 6, 1, 5, 6, 1, 5, 6]
5、成员运算# (案例使用4定义列表):
# 成员运算 ---> in / not in ---> True / False
print(9 in list4) # False
print(1 not in list4) # False
print('red' in list1) # True
6、索引和切片:
# 索引和切片
# 正向索引:0 ~ N-1 / 负向索引:-N ~ -1
7、合并:
list5 = [1, 3, 5, 7, 9]
list6 = [2, 4, 6, 8]
list7 = [3, 6, 9]
temp = list5 + list6
list5 += list6
list6.extend(list7)
print(temp) # [1, 3, 5, 7, 9, 2, 4, 6, 8]
print(list5) # [1, 3, 5, 7, 9, 2, 4, 6, 8]
print(list6) # [2, 4, 6, 8, 3, 6, 9]
8、比较(案例有使用7定义列表):
# 比较
list8 = list(range(1, 9, 2))
list9 = [1, 3, 3, 7, 9]
# 比较两个列表的元素是否意义对应相等
print(list5 == list8) # False
# 比较两个列表对应元素的大小,只要最前面的一个比对方大就是大
print(list9 > list8) # False
9、添加、删除元素和清空列表:
# 添加元素
items = ['a', 'b', 'c', 'd']
items.append('e')
items.insert(1, 'f')
print(items) # ['a', 'f', 'b', 'c', 'd', 'e']
# 删除元素
items.pop()
items.pop(4)
items.remove('a')
print(items) # ['f', 'b', 'c']
# 清空列表元素
items.clear()
print(items) # []
10、查找索引:
# index() ---> 查找元素在列表中的索引(下标)
strs = ['a', 'b', 'c', 'd', 'b', 'e', 'f', 'g', 'h']
if 'k' in strs:
print(items.index('k')) # 不执行
if 'b' in strs:
print(strs.index('b')) # 1
if 'b' in strs[2:]:
print(strs.index('b'), 3) # 1 3
11、获取元素在列表中出现的次数(案例使用10定义列表):
# count() ---> 统计元素在列表中出现的次数
print(strs.count('a')) # 1
print(strs.count('b')) # 2
12、反转(案例使用10定义列表):
# 反转
strs.reverse()
print(strs) # ['h', 'g', 'f', 'e', 'b', 'd', 'c', 'b', 'a']
13、升降排序(案例使用10定义列表):
# 排序,可以修改reverser参数,为false则按升序排列,为True则按降序
strs.sort()
print(strs) # ['a', 'b', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
strs.sort(reverse=True)
print(strs) # ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'b', 'a']
14、抽样:
# sample函数可以对列表元素进行无放回抽样
print(random.sample(strs, k=2))
# choice函数可以对列表元素进行有回放抽样(可以重复抽中)
print(random.choices(strs, k=2))
# choice函数可以从列表中随机选择一个函数
print(random.choice(strs))
15、列表随机排序:
# shuffle函数可以实现列表元素的随机乱序
random.shuffle(strs)
print(strs)