从python

时间:2016-03-17 13:13:18

标签: python recursion

我正在尝试删除列表中的特定单词。让我们说我有以下例子:

a= ['you are here','you are there','where are you','what is that']
b = ['you','what is']

所需的输出应如下:

['are here', 'are there', 'where are', 'that']

我为该任务创建了以下代码:

import re

def _find_word_and_remove(w,strings):
    """
    w:(string)
    strings:(string)
    """
    temp= re.sub(r'\b({0})\b'.format(w),'',strings).strip()# removes word from string
    return re.sub("\s{1,}", " ", temp)# removes double spaces

def find_words_and_remove(words,strings):
    """
    words:(list)
    strings:(list)
    """
    if len(words)==1:
        return [_find_word_and_remove(words[0],word_a) for word_a in strings]
    else:
        temp =[_find_word_and_remove(words[0],word_a) for word_a in strings]
        return find_words_and_remove(words[1:],temp)

find_words_and_remove(b,a)
>>> ['are here', 'are there', 'where are', 'that']

通过使用递归来完成此任务,我似乎过度复杂化“事物”。有没有更简单易读的方法来完成这项任务?

2 个答案:

答案 0 :(得分:3)

您可以使用列表理解:

def find_words_and_remove(words, strings):
    return [" ".join(word for word in string.split() if word not in words) for string in strings]

仅当b中有单个单词时才有效,但由于您的编辑和评论,我现在知道您确实需要_find_word_and_remove()。你的递归方式实在太糟糕了,但如果你不想要递归,那就这样做:

def find_words_and_remove(words, strings):
    strings_copy = strings[:]
    for i, word in enumerate(words):
        for string in strings:
            strings_copy[i] = _find_word_and_remove(word, string)
    return strings_copy

答案 1 :(得分:1)

简单的方法是使用正则表达式:

import re

a= ['you are here','you are there','where are you','what is that']
b = ['you','what is']

你去:

def find_words_and_remove(b,a):
    return [ re.sub("|".join(b), "", x).strip() if len(re.sub("|".join(b), "", x).strip().split(" ")) < len(x.split(' ')) else x for x in a  ]

find_words_and_remove(b,a)
>> ['are here', 'are there', 'where are', 'that']