python - I want to remove all strings from a list of integers. Why doesn't this work?
问题描述
When I run this code, it works, but for some reason it only removes the 'p' and 'h' strings and not the 'z' string. Why?
def filter_list(l):
for item in l:
if item == str(item):
l.remove(item)
return l
print(filter_list([1, 9, 3, 'p', 'z', 7, 'h']))
output:[1, 9, 3, 'z', 7]
解决方案
能做:
def filter_list(l):
return [i for i in l if type(i) is not str]
输出:
>>> filter_list(['e', 'f', 1, 'c', 2, 4])
[1, 2, 4]
l[i]
检查是否不是字符串后仅返回整数
推荐阅读
- asp.net-mvc - MVC 仅从 2 个控制器中选择指定的 id
- c# - 无法更新 mssql 中的小数字段
- android - 在 Android 上读取 x-json-stream
- java - 如何使用 ConstraintLayout 动态创建视图?(不工作)
- jquery - 如何从 JSON 答案在 jQuery 中创建 div 以显示数据?
- android - 在 intellij IDEA 中使用重构提取颤振小部件选项时颤振错误
- javascript - 将所有 javascript 索引增加(或减少)一个数字
- c# - 在 Xamarin Android 上完成多项活动
- javascript - 图案绘图在 Safari 中动态加载行为不端
- scala - Spark中Futures如何保证集群资源的有效利用