Python for循环帮助,附加到列表

时间:2015-11-13 17:15:45

标签: python list loops for-loop

>> find_sub_anagram_in_wordlist('apple', ['ppl','al','app','apple'])

['ppl']

为什么循环不添加其他子字谜?

这是我的代码:

anagramList = []

def find_sub_anagram_in_wordlist(str, str_list):

    global anagramList
    anagramList.clear()
    list1 = list(str)
    list1.sort()
    for word in str_list:
        shouldAdd = True
        listi = list(word)
        listi.sort()
        for j in listi:
            if j in list1:
                list1.remove(j)
            else:
                shouldAdd = False
        if shouldAdd == True:
            anagramList.append(word)
    return anagramList

2 个答案:

答案 0 :(得分:1)

这一行:

if j in list1:
    list1.remove(j)

是你的问题。考虑for word in str_list word == 'ppl

的第一次迭代

记住以下代码:

    for j in listi: #for every char in word, 'p', 'p', 'l'
        if j in list1: 'True for all three
            list1.remove(j) 'removes all three letters
        else:
            shouldAdd = False

这会让您list1 == ['a','e']。您word的下一次迭代会为您提供word == 'al'。如果我们再次查看上述代码,您会看到'l' list1中不再有shouldAdd == False。另外,由于a就在其中,现在它不是list1 == ['e']。你可以看到它的发展方向。

使用您的代码,您可以通过将list1 = list(str)移动到for word in str_list:循环内部来解决此问题,以便每次都重新初始化列表。我将尝试找到一种更加pythonic的方式来执行该功能并在我可以的时候发布它。

编辑:

这是我这样做的方式:

>>> def is_sub_anagram(s, sub):
    s = list(s)
    try:
        for c in sub: s.remove(c)
    except:
         return False
    return True
>>> def find_sub_anagram_in_wordlist(s, str_list):
    return list(filter(lambda x: is_sub_anagram(s,x), str_list))

>>> find_sub_anagram_in_wordlist('apple',['app','ppl','ae','le'])
['app', 'ppl', 'ae', 'le']

>>> find_sub_anagram_in_wordlist('apple',['app','ppl','ae','le','lle'])
['app', 'ppl', 'ae', 'le']

答案 1 :(得分:1)

我认为这有助于简化您的工作。特别是,将功能上的海鞘测试与过滤候选者的程序分开。这将是我的方法:

def is_sub_anagram( word, candidate ):
    word = list( word )
    for letter in candidate:
        try:
            word.remove( letter )
        except ValueError:
            return False
    return True


def filter_sub_anagrams( word, candidates ):
    return [ x for x in candidates if is_sub_anagram( word, x ) ]


print( filter_sub_anagrams( 'apple', [ 'ppl', 'al', 'app', 'apple', 'aapl' ] ) )

输出结果为:

['ppl', 'al', 'app', 'apple']

请注意,'aapl'不会也不应包含在输出中。

相关问题