[英]What is the efficient way to check a present of a string in a single element list in python
I have a single element list like below我有一个如下所示的单个元素列表
listx=['Digital Operations']
My goal is to just check if the word 'Digital' is present in the list listx我的目标是检查列表 listx 中是否存在“数字”一词
I wrote the below code我写了下面的代码
if any('Digital') in listx:
print("the word digital is present")
else:
print("word Digital not found")
I am getting the output "word Digital not found" despite it being clearly there.我得到了 output “word Digital not found”,尽管它显然在那里。 What am i doing wrong?
我究竟做错了什么?
Try this:-尝试这个:-
listx=['Digital Operations']
if 'Digital' in listx[0]:
print("the word digital is present")
else:
print("word Digital not found")
Output:- Output:-
the word digital is present
the any()
function takes an iterable (for example a list) and returns True
if any of its values is True
. any()
function 接受一个可迭代对象(例如一个列表),如果其中任何一个值为True
True
You are calling it with a str
wich will evaluate to True
So basically your if statement then says你用
str
调用它,它将评估为True
所以基本上你的 if 语句然后说
if True in listx:
which will in turn evaluate to False
, causing your problem.这将反过来评估为
False
,从而导致您的问题。
If you would like to use any()
you could use a list comprehension like this:如果你想使用
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")
For a more efficent version you can use a generator expression that replaces the need for listy
and combines it into the if
-statement like this:对于更有效的版本,您可以使用生成器表达式来替换对
listy
的需求并将其组合到if
语句中,如下所示:
if any('Digital' in elem for elem in listx):
thank's to wjandrea comment感谢 wjandrea 的评论
any()
checks for True
values, so if you change your first line to any()
检查True
值,因此如果您将第一行更改为
if any(any([x=='Digital' for x in y.split()]) for y in listx):
You should be fine.你应该没事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.