6番目の講義:Pythonのリストと追加、削除、変更、検索と並べ替え、リストの理解


1.リストの作成

#列表
lst=['hello','world',98]
print(id(lst))
print(type(lst))
print(lst)
lst2=list(['hello','world',18])
print(id(lst2))
print(type(lst2))
print(lst2)
print(lst2[0]) #hello

2.リストを追加、削除、変更、および確認します

2.1関連する検索


#查找
lst=['he','world','he']
print(lst.index('he')) #返回的0,列表种有相同元素只返回列表中相同元素的第一个元素索引
print(lst.index('he',1,3)) #2,从1到3中找he的位置

#获取列表中的单个元素
lst=['he',100,'world','he']
print(lst[2]) #world
print(lst[-3]) #100

#获取列表中的多个元素
lst=[1,2,3,4,5,6]
print(lst[1:4:2]) #[2,4] 开始 结束 步长
print(lst[2:5]) #[3,4,5] 默认步长为1
print(lst[2:5:]) #[3,4,5] 默认步长为1
print(lst[:6:2])#[1,3,5] 默认从起始
print(lst[1::2])#[2,4,6] 从后往前走
print(lst[::-1]) #[6,5,4,3,2,1] 逆序输出
print(lst[6::-1]) #[6,5,4,3,2,1] 逆序输出

#判断指定元素在列表中是否存在
lst=['he',100,'world','he']
print(100 in lst) #True
print(100 not in lst) #False

#遍历
for item in lst:
    print(item)

2.2増加

lst=[10,20,30]
print('添加元素之前:',lst,id(lst)) #添加元素之前: [10, 20, 30] 2604711344704
lst.append(40)
print('添加元素之后:',lst,id(lst)) #添加元素之后: [10, 20, 30, 40] 2604711344704
lst2=['11d','213d']
lst.extend(lst2) #向列表末尾添加多个
print(lst) #[10, 20, 30, 40, '11d', '213d']
lst.insert(0,90) #在第一个位置插入90
print(lst) #[90, 10, 20, 30, 40, '11d', '213d']
lst3=[True,False,'sjf']
lst[1:]=lst3 #切掉lst从1以后的,用lst3替换
print(lst) #[90, True, False, 'sjf']

2.3削除

lst=[10,20,30,40,30]
lst.remove(30) #从列表中移除1个元素,如果有重复的元素只移动第一个
print(lst) #[10, 20, 40, 30]
lst.pop(0) #移除第一个元素,如果指定的索引不存在,则抛出异常
print(lst) #[20, 40, 30]
lst.pop()
print(lst) #[20, 40],出栈,删除最后一个元素

#切片操作,删除至少一个元素,产生一个新的列表对象
lst=[10,20,30,40,30]
new_lst=lst[1:3]
print('原列表',lst) #原列表 [10, 20, 30, 40, 30]
print('切片后的列表',new_lst) #切片后的列表 [20, 30]

#不产生新的列表对象,只是删除原列表种的内容
lst[1:3]=[]
print(lst) #[10, 40, 30]

#清楚列表中所有元素
lst.clear()
print(lst) #[]
#删除这个列表
del lst
print(lst)

2.4変更

lst=[10,20,30,40,30]
#一次修改一个值
lst[0]=100
print(lst) #[100, 20, 30, 40, 30]
#修改多个值
lst[1:3]=[300,400,500,600]
print(lst) #[100, 300, 400, 500, 600, 40, 30]

3.並べ替え

lst=[20,40,10,30,0]
lst.sort() #默认升序
print(lst) #[0, 10, 20, 30, 40]

lst.sort(reverse=True) #降序
print(lst) #[40, 30, 20, 10, 0]

#内置函数排序,会产生新的列表对象
lst=[20,40,10,30,0]
new_list=sorted(lst)
sorted(lst,reverse=True)
print(new_list) #[0, 10, 20, 30, 40]

4.リストの生成式

ist=[i for i in range(1,10)]
print(ist) #[1, 2, 3, 4, 5, 6, 7, 8, 9]

ist=[i*i for i in range(1,10)]
print(ist) #[1, 4, 9, 16, 25, 36, 49, 64, 81]

lst2=[i*2 for i in range(1,10)]
print(lst2) #[2, 4, 6, 8, 10, 12, 14, 16, 18]

おすすめ

転載: blog.csdn.net/buxiangquaa/article/details/113976063