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

2024-09-24 22:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

>> 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

Tags: inappleforfindsortppllistword
2条回答

这条线:

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'。如果我们再看一遍上面的代码,您将看到,因为在list1shouldAdd == False中不再有'l'。而且,因为a在里面,所以现在不是了。你可以看到这是怎么回事。你知道吗

使用您的代码,您可以通过将list1 = list(str)移动到for word in str_list:循环的内部来解决这个问题,这样每次它都会重新初始化列表。我将尝试找到一个更为python的方法来完成这个函数,并在我可以的时候发布它。你知道吗

编辑:

以下是我的方法:

>>> 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']

我认为这有助于简化你的工作。特别是,从功能上把子项的测试与筛选候选项的过程分开。这就是我的方法:

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'不是也不应该包含在输出中。你知道吗

相关问题 更多 >