1

I have a list of words like the following:

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

The output I need is:

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

In order to do this, I came up with a loop:

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)

It's simply not working. I'm getting something like:

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

I'm sure I'm just doing one simple thing wrong but I can't see it. And I would use list.append() if there's an easy way to implement it.

Thanks!

4

6 回答 6

5

这并不能直接解决您的问题(为什么您尝试的代码不能按预期工作),但我建议首先不要使用循环 - 相反,有一个专门的函数来给出给定英文单词的单数形式,喜欢:

def singular(word):
  # ...
  return singularForm

然后使用列表理解

new_list = [singular(word) for word in old_list]

它更短,恕我直言,很好地传达了你所做的事情:获取每个单词的单数形式,old_list而不是谈论它是如何完成的(通过循环遍历列表)。

于 2013-10-08T10:42:36.713 回答
5

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

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])
于 2013-10-08T10:43:07.343 回答
4

如果有一种简单的方法来实现它,我会使用 list.append() 。

我认为你误解了它的list.append()工作原理。请记住,列表是可变的,因此您不需要执行new_list1[:0] = blah. 你可以这样做:

new_list = []
for word in old_list:
    if word.endswith("ies"):
        new_list.append(word.replace("ies","y"))
    elif word.endswith("s"):
        new_list.append(word.replace(' ',''))

此外,我没有看到您的第二个替换功能应该是什么。如果您想摆脱's'(对于诸如 等词'houses'),您可以使用切片:

>>> print 'houses'[:-1]
house
于 2013-10-08T10:36:06.317 回答
0

您可以在一行中轻松完成此操作。

new_list = [word[:-1].replace('ie','y') for word in old_list]

请注意“pies”之类的词,因为代码会将其变成“py”。也许那是 Python 试图向我们发送秘密消息。;)

于 2013-10-08T11:06:06.223 回答
0
#Use list comprehension to less code#
old_list = ['houses','babies','cars','apples']
new_list = ['house','baby','car','apple']
new_list+=[word.replace('ies','y') for word in old_list if word.endswith('ies')]
于 2013-10-08T10:52:35.530 回答
0
old_list = ['cars', 'babies', 'computers', 'words']

def remove_s_ies(string):
    if string.endswith('ies'):
        return string[:-3]+'y'
    elif string.endswith('s'):
        return string[:-1]


new_words = [ remove_s_ies(word) for word in old_list ]
于 2013-10-08T12:07:39.867 回答