检查列表中的任何值是否存在于senten中

2024-10-01 04:53:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在检查列表中的值是否存在于以下句子中:

rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]

whoAmI = "I am an Engineer"

if rich.*MISSING_HERE* in whoAmI:
    print "You are RICH"
else :
    print "You are POOR"

如果您查看带有If语句的行,我将检查rich中是否有任何元素在whoAmI中可用。我怎么检查这个?你知道吗


Tags: you列表amare句子programmerprintdoctor
3条回答

使用any()方法-

if any(r in whoAmI for r in rich):
    print "You are RICH"
else :
    print "You are POOR"

我们可以使用Python库的re或regex模块来搜索字符串中的单词。我们将使用simpleforloop(注:时间复杂度:O(n))

import re

rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]

whoAmI = "I am an Businessman"

for word in rich:
    if re.search(i, whoAmI):
        print("Rich")
        quit()

print("Poor")

我们使用Python内置函数quit(),以防止相同的输出多次显示。你知道吗

试试for else循环

rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Engineer"

for r in rich:
    if r in whoAmI:
        print "You are RICH"
        break
else:
    print "You are POOR" 

相关问题 更多 >