如何在python的def中应用两个if

2024-09-25 06:24:09 发布

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

input=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt')

我想要一个看起来像

output=('befel','recal','expel','swel','test','mark','scott','brutt')

就像如果单词以'ed'结尾,去掉'ed'否则返回到类似的单词,第二个条件是如果单词在应用第一个条件后以'll'结尾,然后去掉'l'并返回输出

我想申请两个条件

首先if将检查以“ed”结尾的所有单词,然后这个if将从满足第一个if的单词中删除最后两个字母。你知道吗

然后我想应用第二个if,它将查找所有以'll'结尾的单词

words=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt') . 
def firstif(words):  
    for w in words:  
        if w.endswith('ed'):  
             return (w[:-2]) . 
        else:  
            return(w) . 
firstif(w) . 
words2=tuple(firstif(w)) . 
def secondif(words2):  
    for w2 in words2:  
        if w2.endswith('ll'):  
            return (w2[:-1]) . 
        else:  
            return(w2) . 
secondif(w2)

这段代码正在运行,但给我奇怪的输出


Tags: returnif结尾条件单词scottwordsll
3条回答

我也可以使用elif

words=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt')
a=[]
for w in words:
    if w.endswith("lled"):
        a.append(w[:-3])    
    elif w.endswith("ed"):
        a.append(w[:-2])
    else:
        a.append(w)

结果

>>>tuple(a)
('befel', 'recal', 'expel', 'swel', 'test', 'mark', 'scott', 'brutt')

使用嵌套循环来检查将是一个更好的主意。试试看:

words=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt') . 
def fix_word(words):
    temp = []
    for w in words:
        if w.endswith('ed'):
            if w.endswith('lled'):
                temp.append(w[:-3])
            else:
                temp.append(w[:-2])
        else:
            temp.append(w)
    return tuple(temp)

另一种方法是使用map()

注意:我不建议您使用input作为变量名,因为还有一个名为input()的函数。你知道吗

def check(word):
    temp_word = word[:-2] if word.endswith('ed') else word
    return temp_word[:-1] if temp_word.endswith('ll') else temp_word

user_input=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt')

res = tuple(map(check, user_input))

结果:

res
('befel', 'recal', 'expel', 'swel', 'test', 'mark', 'scott', 'brutt')

相关问题 更多 >