input=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt')
我想要一个类似
的输出output=('befel','recal','expel','swel','test','mark','scott','brutt')
这就像单词以“ ed”结尾,删除“ ed”,否则返回相似的单词,第二个条件是,如果单词在应用第一个条件后以“ ll”结尾,然后删除“ l”并返回输出
我想应用两个ifs
首先,if将检查所有以“ ed”结尾的单词,然后if将从满足第一个if的单词中删除最后两个字母。
然后,如果要查找以'll'结尾的所有单词s,我想再加上第二个
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)
这段代码正在运行,但是给了我奇怪的输出
答案 0 :(得分:0)
使用嵌套循环进行检查将是一个更好的主意。只需尝试:
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)
答案 1 :(得分:0)
我也可以使用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')
答案 2 :(得分:0)
使用 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')
答案 3 :(得分:0)
您可以以 pythonic 方式(一行)
解决它words = ['befelled','recalled','expelled','swelled','tested','marked','scott','brutt']
clean_words = [(e[:-3] if e.endswith('lled') else e[:-2] if e.endswith('ed') else e ) for e in words ]
答案 4 :(得分:0)
You can also use slicing.
inputs=('befelled','recalled','expelled','swelled','tested','marked','scott','brutt')
def clean_word(words):
result = []
for word in words:
if word[-4:] == 'lled':
result.append(word[:-3])
elif word[-2:] == 'ed':
result.append(word[:-2])
else:
result.append(word)
return result
print(clean_word(inputs))