“if”语句中的“For”循环(继续为“elif”)语句

2024-09-21 11:42:54 发布

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

我有一组if、elif和else语句。if语句比较列表中的项,然后对找到的项执行操作。elif和else不会对列表做任何操作,所以我不认为将所有这些都放在for循环中有什么意义。在

if myText.count(myItem for myItem in myList):
    doSomething using myText and myItem
elif otherThing1:
    doStuff
elif otherThing2:
    doOther stuff
else:
    forget this, go have a drink

当然,我在第一行中遇到了一个错误,但是有没有一种python方法可以在不需要重新构造整个代码的情况下获得我要寻找的东西?在


Tags: andin列表forifcount语句else
3条回答
for myItem in myList :
    if myItem in myText :
        doSomething using myText and myItem
    elif otherThing1:
        doStuff
    elif otherThing2:
        doOther stuff
    else:
        forget this, go have a drink

你的话:
“我想看看str列表中的str是否在更大的str(myText)中,然后对myItem和myText执行操作。我只希望在if语句遍历myList的所有项后执行“else”位,但没有找到任何内容。”

count = 0
for myItem in mylist:
    if myItem in myText:
        count += 1
        do something with myItem and myText
if count == 0:
    do what you want to do when if finds nothing

我真的不知道你在做什么elifs?您正在寻找较大字符串中的子字符串。它的结果是真是假。为什么你需要4个逻辑语句?在


您必须认识到,如果您将if/else语句放在循环中,那么每次循环运行时,它都会执行求值为True或False的操作

如果您只是想测试某项是否在列表中,一种简单的方法是:

if item in list:
    do something

相关问题 更多 >

    热门问题