python中移除列表元素所遇到的坑
程序员文章站
2024-01-22 15:46:04
题目:移除列表中除字符串外的元素方法1:移除时考虑元素位置的改变**#修改前list_3 = ["abc","2",2,4.4,"4.4","",99,"abcd",666,"777","444.4",444.4][list_3.remove(i) for i in list_3 if 'str' not in str(type(i))] print(list_3) #['abc', '2', 4.4, '4.4', '', 'abcd', '777', '444.4']#分析原因:由于移...
题目:移除列表中除字符串外的元素
方法1:移除时考虑元素位置的改变
**
#修改前
list_3 = ["abc","2",2,4.4,"4.4","",99,"abcd",666,"777","444.4",444.4]
[list_3.remove(i) for i in list_3 if 'str' not in str(type(i))]
print(list_3) #['abc', '2', 4.4, '4.4', '', 'abcd', '777', '444.4']
#分析原因:由于移除列表中的元素,导致列表中元素的位置发生改变,从而引起有的元素未按题意中移除
#修改后
list_3 = ["abc","2",2,4.4,"4.4","",99,"abcd",666,"777","444.4",444.4]
i = 0
while i < len(list_3):
if not isinstance(list_3[i],str):
list_3.remove(list_3[i])
i = i
else:
i = i+1
print(list_3) #['abc', '2', '4.4', '', 'abcd', '777', '444.4']
方法2:用另一个列表接受要移除的数据,然后在遍历移除
list_3 = ["abc","2",2,4.4,"4.4","",99,"abcd",666,"777","444.4",444.4]
remove_list = [k for k in list_3 if not isinstance(k,str)]
result_list = [list_3.remove(j) for j in remove_list]
print(list_3) #['abc', '2', '4.4', '', 'abcd', '777', '444.4']
#同理,遍历字典是不能移除字典中的键值对,因为元素位置发生了改变
纸上得来终觉浅,绝知此事要躬行。
本文地址:https://blog.csdn.net/weixin_43509698/article/details/107305072