Python for循环帮助,附加到列表
为什么循环不添加其他子字谜 这是我的密码:Python for循环帮助,附加到列表,python,list,loops,for-loop,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)
>> 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
这是你的问题。想想stru列表中word的第一次迭代,其中word='ppl
请牢记以下代码:
if j in list1:
list1.remove(j)
这就给您留下了list1=['a','e']
。对word
的下一次迭代将为您提供word=='al'
。如果我们再次查看上述代码,您将看到,由于在list1
中不再有'l'
,应该添加==False
。而且,因为a
在它里面,所以它现在不在了,list1=['e']
。你可以看到这是怎么回事
使用您的代码,您可以通过将list1=list(str)
移动到for-word-in-stru-list:
循环的内部来修复此问题,以便它每次都重新初始化列表。我将尝试找到一种更具python风格的方法来完成这个函数,并在可能的时候发布它
编辑:
以下是我的做法:
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
我认为这将有助于简化你的工作。特别是,从功能上将子匿名性测试与筛选候选项的过程分开。这就是我的方法:
>>> 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' ] ) )
请注意,'aapl'
不是也不应该包含在输出中。您实际上希望从这段代码中获得什么?第二个参数是要检查的字符串列表,无论它们是否是第一个参数的子字谜。我希望代码检查第二个参数中列表的每个元素,如果它是第一个参数的子字谜,则将其添加到单独的列表中,然后在最后返回子字谜列表。为清晰起见,请编辑代码以显示所需的输出。list
对象没有属性clear
。你能展示一些真正有效的代码吗?非常感谢你的帮助,我非常感谢@我的思想是你的吗?你的想法是我的吗?天哪,我们谁是真的?!非常感谢你的帮助,我非常感激!
['ppl', 'al', 'app', 'apple']