Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字典中使用Counter()为字谜寻找关键字_Python_Anagram - Fatal编程技术网

Python 在字典中使用Counter()为字谜寻找关键字

Python 在字典中使用Counter()为字谜寻找关键字,python,anagram,Python,Anagram,我试图在一个虚构的单词中寻找具有类似字母(拼音)的键,我有一个不完整的代码: from collections import Counter diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'} word = input('what is the word?') new=[] for i in dic: if(Counter(word) == Counter(....): new.append(...) else:

我试图在一个虚构的单词中寻找具有类似字母(拼音)的键,我有一个不完整的代码:

from collections import Counter
diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'}
word = input('what is the word?')
new=[]
for i in dic:
    if(Counter(word) == Counter(....):
        new.append(...)
    else:
        continue
 
print(f'{word} and {new} are anagrams')

我不知道如何检查键以及它们是否与给定的输入匹配。感谢您的帮助

我实际上认为
计数器
是一个很好的解决方案,可能比排序更好,因为它是O(n)。例如,
Counter(“arc”)==Counter(“car”)
返回
True
。所以你走对了方向

您的代码中有拼写错误(
dic
应该是
diction
)。您的for循环已经在遍历键,因此您很接近:

from collections import Counter
diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'}
word = input('what is the word?')
new=[]
for i in diction:
    if(Counter(word) == Counter(i)):
        new.append(i)
    else:
        continue
 
print(f'{word} and {new} are anagrams')
如果我输入“tac”,它将打印:

tac和['cat']是字谜


你如何定义“相似”?要检查字谜,如果单词的长度相同,请对字母进行排序并检查是否相等。这是我在stackoverflow上的第一个问题:)我正在尝试使用Json格式的英语词典,我不想浏览定义,所以我的目标只是键。这样,我将根据字典条目而不是定义匹配输入。。谢谢你的支持help@user80322至于第一个问题,你做得很好,所以我给了你一票!欢迎来到StackOverflow!