首页 > 解决方案 > 检查列表中的项目是否包含数字

问题描述

我一直在尝试遍历列表以找到第一个包含数字的项目。我遇到了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

如果有人可以提示正确的方法,那就太好了。

标签: pythonstringlistfor-loopinteger

解决方案


这是一个可能的解决方案(lst是您的字符串列表):

idx = next((i for i, x in enumerate(lst) if any(c.isdigit() for c in x)),  -1)

idx将是包含数字的第一个元素的索引,或者-1如果这样的元素不存在。


推荐阅读