['python'安卓通用版
发布日期:2024-06-08 19:58 点击次数:147
List(列表)是Python中使用最多的一种数据结构,以下是我方转头的几大列表顺序,仅供参考。
1、List 添加元素
append():用于在列表的末尾追加任何数据类型的元素,被追加的元素在List中保握着原结构类型。
list1 = [1,2,3,4]list1.append('python')# list1 = [1, 2, 3, 4, 'python']list2 = ['python','当打之年']list1.append(list2)# list1 = [1, 2, 3, 4, 'python', ['python', '当打之年']]
extend():将一个列表中每个元素循序辨认添加到另一个列表中。
list1 = [1,2,3,4]list2 = ['python','当打之年']list1.extend(list2)# list1 = [1, 2, 3, 4, 'python', '当打之年']
insert():将指定的对象插入到列表中指定的位置。
list1 = [1,2,3,4]list2 = ['python','当打之年']list1.insert(1,list2)# list1 = [1, ['python', '当打之年'], 2, 3, 4]
2、List 删除元素
remove():按值删除,删除指定值元素,只会删除第一个和指定值疏导的元素。
list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']list1.remove('python')# list1 = [1, 2, 3, 4, '当打之年', 'python']
del(): 按索引删除,删除指定索引元素,不错删除单个索引元素,也可删除流通索引元素。
list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']del list1[1]# list1 = [1, 3, 4, 'python', '当打之年', 'python']list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']del list1[1:5]# list1 = [1, '当打之年', 'python']
pop(): 按索引删除,删除指定索引元素,只能删除单个元素,若索引不详则删除临了一个元素(常用)。
list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']list1.pop(0)# list1 = [2, 3, 4, 'python', '当打之年', 'python']list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']list1.pop()# list1 = [1, 2, 3, 4, 'python', '当打之年']
clear(): 删除列表总计元素。
list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']list1.clear()# list1 = []
3、List 切片
语法:list[start:end:step],取得指定范围的子集,参数均可不详。
list1 = [1, 2, 3, 4, 'python', '当打之年', 'python']list2 = list1[1:6:2]# list2 = [2, 4, '当打之年']list2 = list1[:6:2]# list2 = [1, 3, 'python']list2 = list1[1::2]# list2 = [2, 4, '当打之年']list2 = list1[1:6:]# list2 = [2, 3, 4, 'python', '当打之年']list2 = list1[::-1]# list2 = ['python', '当打之年', 'python', 4, 3, 2, 1]
4、List 遍历
频频用法:
list1 = ['python', '当打之年', 'python']for i in range(len(list1)): print(i, '--', list1[i])# 0 -- python# 1 -- 当打之年# 2 -- python
高等用法:
list1 = ['python', '当打之年', 'python']for index, data in enumerate(list1): print(index, '--',data)# 0 -- python# 1 -- 当打之年# 2 -- python
5、赶紧取得 List 元素
random.choice()顺序
import randomlist1 = [1, 2, 3, 4, 'python', '当打之年', 'python']data1 = random.choice(list1)# 2data2 = random.choice(list1)# 当打之年data3 = random.choice(list1)# 3
6、List 排序
sort():在原列内外面进行排序
list1 = [5, 2, 3, 7, 0, 4, 3, 9, 6]list2 = list1.sort()# list1 = [0, 2, 3, 3, 4, 5, 6, 7, 9]# list2 = None
sorted():内置函数,生成新的列表,不更动原列表
list1 = [5, 2, 3, 7, 0, 4, 3, 9, 6]list2 = sorted(list1)# list1 = [5, 2, 3, 7, 0, 4, 3, 9, 6]# list2 = [0, 2, 3, 3, 4, 5, 6, 7, 9]
7、判断 List 是否为空
if list1 == []: print('空列表') if len(list1) == 0: print('空列表') if not list1: print('空列表')
8、列表推导式
列表式代码优雅,但一般比拟复杂的法子惨酷少用(阅读性较差)
# 单一元素list1 = [i*5 for i in range(5)]print('list1 = '安卓通用版,list1)# list1 = [0, 5, 10, 15, 20]# 加多判断要求list1 = [2, 4, 5, 6, 3]list2 = [i*3 for i in list1 if i < 5]print('list2 = ',list2)# list2 = [6, 12, 9]# 多重轮回list1= [1, 2, 3]list2 =[4, 5, 6]list3 = [x+y for x in list1 for y in list2]# list3 = [5, 6, 7, 6, 7, 8, 7, 8, 9]