[英]Check if item in list contains a number
我一直在嘗試遍歷列表以找到包含數字的第一個項目。 我遇到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
如果有人可以提示正確的方法,那就太好了。
假設您列表中的內容是字符串,則以下內容應該有效:
list1 = ['Hello', 'World(2)', 'Bye 3']
# For each string in the list
for s in list1:
# If any of the characters in the string are digits:
if any(c.isdigit() for c in s):
# Print the string and stop searching the list.
print(s)
break
輸出:
World(2)
這是一個可能的解決方案( lst
是您的字符串列表):
idx = next((i for i, x in enumerate(lst) if any(c.isdigit() for c in x)), -1)
idx
將是包含數字的第一個元素的索引,如果這樣的元素不存在,則為-1
。
你已經有一些很好的答案,但這里有另一個:
list1 = ['Hello', 'World(2)', 'Bye 3']
numbers = ['1','2','3','4','5','6','7','8','9','0']
for x in list1:
if any(a in x for a in numbers):
print(x)
break
World(2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.