Skip to main content
 首页 » 编程设计

python之在 python 中对列表使用 if 语句

2025年05月04日8luoye11

我有一个单词列表,如下所示:

old_list = ['houses','babies','cars','apples'] 

我需要的输出是:

new_list = ['house','baby','car','apple'] 

为了做到这一点,我想出了一个循环:

new_list1 = [] 
new_list2 = [] 
for word in old_list: 
    if word.endswith("ies"): 
        new_list1[:0] = [word.replace("ies","y")]  
    elif word.endswith("s"): 
        new_list2[:0] = [word.replace(' ','')[:-1]] 
 
new_list = new_list1 + new_list2 # Order doesn't matter, but len(new_list) == len(old_list) 

它根本不起作用。我得到类似的东西:

new_list = ['baby','house','babie','car','apple'] 

我确定我只是做错了一件简单的事情,但我看不到它。如果有一种简单的方法来实现它,我会使用 list.append()。

谢谢!

请您参考如下方法:

首先,word.replace("ies","y") 不是一个好主意;有时您可以在单词的中间找到它,例如柴油

new_list = [] 
for word in old_list: 
    if word.endswith("s"): 
        if word.endswith("ies"): 
            new_list.append(word[:-3] + "y") 
        else: 
            new_list.append(word[:-1])