python - 检查列表中的项目是否包含数字
问题描述
我一直在尝试遍历列表以找到第一个包含数字的项目。我遇到了any()
它似乎无法“搜索”列表项目中的数字。
如果我以以下列表为例:
["Hello", "World(2)", "Bye 3"]
列表中包含数字的第一项位于位置 1 [World(2)]。
第一次出现“携带”数字后的以下某些项目是否无关紧要。
我从以下内容开始:
list1 = ["Hello", "World(2)", "Bye 3"]
for x in list1:
if x is.digit(): #this method doesn't work because it's only true when the whole item contains numbers.
x = first_item_where_a_number_appears
如果有人可以提示正确的方法,那就太好了。
解决方案
这是一个可能的解决方案(lst
是您的字符串列表):
idx = next((i for i, x in enumerate(lst) if any(c.isdigit() for c in x)), -1)
idx
将是包含数字的第一个元素的索引,或者-1
如果这样的元素不存在。
推荐阅读
- symfony - 给定“字符串”、“App\Entity”类型的预期参数
- java - 我的报告日志在范围报告中因不同类别而混杂在一起
- react-select - 每个菜单选项都呈现为选中状态。奇怪的解决方法
- css - 有没有办法用 CSS 重命名列表中的第 n 个项目?
- html - sass如何更改类下所有链接的颜色?
- r - shinydashboard:使用 uiOutput() 进行正文时出现奇怪的渲染
- mysql - 数据库中表之间的关系是否加快了查询的性能?
- php - 我可以使用类似的 `dirname(__FILE__) 吗?` 导入这样的 PHP 文件?
- menu - 引导程序 4 菜单
- php - 想要从文件夹中删除孤立图像