python - 使用 isdigit() 字符串方法时出现错误
问题描述
不是超级有经验,但我在使用 isdigit() 方法时遇到了一个错误。
我正在尝试浏览一个列表并删除所有非数字,但是我的最终列表不断给我一些字母。不确定这是一个错误还是我做错了什么。
这是我当前的python:
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
我的代码:
>>> test
['b', 'd', 'f', 'h', 'j', 'l', 'x', '2']
>>> for i in test:
if not i.isdigit():
print(i, "should not be a digit")
test.remove(i)
b should not be a digit
f should not be a digit
j should not be a digit
x should not be a digit
>>> test
['d', 'h', 'l', '2']
在这里,我希望我的最终列表中只有 2 个。我做错了吗?
解决方案
如果你想过滤掉一个isdigit
测试:
test = list(filter( lambda x : x.isdigit(), test))
正如评论中所说,在迭代时删除元素是不好的做法。
推荐阅读
- css - 有没有办法阻止 Shiny 引用 Bootstrap 3 共享文件夹?
- git - 仍然提示进行令牌身份验证,即使它保存在配置中
- azure - Visual Studio Code - Azure Functions - 新建项目按钮消失
- ajax - 如何以编程方式使用 ajax 添加微调器以选择列表?
- sql - 使用 RODBC 从 R 写入数据库:sqlSave 不起作用
- android - 滑动以更改位置 0 项的 RecyclerView 的内容(和排序顺序)会导致列表滚动
- elasticsearch - 弹性 match_phrase_prefix 设置单词顺序
- api - GitLab API - 获取总体代码行数
- antd - 如何让 AntD 中的下拉菜单不显示旁边的三个小点?
- python - Discord.py 从下拉菜单中添加角色