【问题标题】:Python for loop help, appending to listsPython for 循环帮助,附加到列表
【发布时间】:2015-11-13 17:15:45
【问题描述】:
>> 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

【问题讨论】:

  • 你真正想从这段代码中实现什么?
  • 第二个参数是一个字符串列表,要检查它们是否是第一个参数的子变位词。我希望代码检查第二个参数中列表的每个元素,如果它是第一个参数的子字谜,则将其添加到单独的列表中,然后最后我想返回子字谜列表。
  • 为清楚起见,请编辑您的代码以显示所需的输出。
  • list 对象没有属性clear。你能展示一些实际有效的代码吗?

标签: python list loops for-loop


【解决方案1】:

我认为这将有助于简化您的工作。特别是,在功能上将 subanagramness 测试与筛选候选人的过程分开。这将是我的方法:

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

【讨论】:

  • 非常感谢您的帮助,非常感谢!
  • @RNar 我的想法是你的吗?你的想法是我的吗?天哪,我们谁是真的?!
【解决方案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 == ['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']

【讨论】:

  • 非常感谢您的帮助,非常感谢!
猜你喜欢
  • 2021-05-31
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
  • 2020-03-26
  • 2012-06-10
相关资源
最近更新 更多