列表直接刪除元素
方法一: remove: 刪除單個元素,刪除首個符合條件的元素,按值刪除
str = [1,2,3,4,3,5,6,2]
str.remove(3)
print(str) ?# [1, 2, 4, 3, 5, 6, 2]
方法二: pop: 刪除單個或多個元素,按位刪除(根據(jù)索引刪除), 刪除時會返回被刪除的元素
str_pop= [1,2,3,4,3,5,6,2]
str_pop.pop(3)
print(str_pop) ?# [1, 2, 3, 3, 5, 6, 2]
方法三: del: 根據(jù)索引刪除
str_del= [1,2,3,4,3,5,6,2]
del str_del[1]
print(str_del) ?# [1, 3, 4, 3, 5, 6, 2]
列表遍歷過程中刪除元素, 會造成不可預(yù)知錯誤, 可使用下面幾種方法刪除
方法一: 列表推導(dǎo)式
# 刪除 <4
list1 = [1, 2, 3, 4, 5, 6]
new_list1 = [i for i in list1 if i > 4]
print(new_list1)
方法二: filter + lambda
# 刪除 <4
list2 = [1, 2, 3, 4, 5, 6]
new_list2 = filter(lambda i: i > 4, list2)
print(list(new_list2))
方法三: 倒序遍歷
# 刪除 >4
list3 = [1, 2, 3, 4, 5, 6]
for i in range(len(list3)-1, -1, -1):
? ? if list3[i] > 4:
? ? ? ? list3.remove(list3[i])
print(list3)
方法四:文章來源:http://www.zghlxwxcb.cn/news/detail-524155.html
# 刪除 >4
list4 = [1, 2, 3, 4, 5, 6]
new_list4 = []
for i in list4:
? ? if i <= 4:
? ? ? ? new_list4.append(i)
print(new_list4)
?文章來源地址http://www.zghlxwxcb.cn/news/detail-524155.html
到了這里,關(guān)于python列表刪除元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!