簡體   English   中英

在 python 的單個元素列表中檢查字符串是否存在的有效方法是什么

[英]What is the efficient way to check a present of a string in a single element list in python

我有一個如下所示的單個元素列表

listx=['Digital Operations']

我的目標是檢查列表 listx 中是否存在“數字”一詞

我寫了下面的代碼

if any('Digital') in listx:
  print("the word digital is present")
else:
  print("word Digital not found")

我得到了 output “word Digital not found”,盡管它顯然在那里。 我究竟做錯了什么?

嘗試這個:-

listx=['Digital Operations']

if 'Digital' in listx[0]:
    print("the word digital is present")
else:
    print("word Digital not found")

Output:-

the word digital is present

any() function 接受一個可迭代對象(例如一個列表),如果其中任何一個值為True True 你用str調用它,它將評估為True所以基本上你的 if 語句然后說

if True in listx:

這將反過來評估為False ,從而導致您的問題。

如果你想使用any()你可以使用這樣的列表推導:

listx = ['Digital Operations']

listy = ['Digital' in elem for elem in listx]
if any(listy):
  print("the word digital is present")
else:
  print("word Digital not found")

對於更有效的版本,您可以使用生成器表達式來替換對listy的需求並將其組合到if語句中,如下所示:

if any('Digital' in elem for elem in listx):

感謝 wjandrea 的評論

any()檢查True值,因此如果您將第一行更改為

if any(any([x=='Digital' for x in y.split()]) for y in listx):

你應該沒事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM