【问题标题】:anagram finder using tuples and dictionaries使用元组和字典的字谜查找器
【发布时间】:2013-03-25 17:51:04
【问题描述】:

所以我有一个程序,它接受一个字符串,并返回一个元组,其中字符串中的所有字母按排序顺序。

然后程序需要创建一个字典,以元组作为键,值是所有带有键的单词的列表

到目前为止,我有:

_DEBUG = True
def getLetters(string):
    """Purpose, to nab letters from a string and to put them in a tuple in
    sorted order."""
    #sort the letters and put them in a tuple
    tuple_o_letters = tuple(sorted(string))
    if _DEBUG:

    print tuple_o_letters
    return tuple_o_letters
def main():
    try:# open the file
        fin = open("words2.txt")
    except:
        #if file doesn't exist
        print("no, no, file no here.")
        sys.exit(0)
    wordList = [] #create a word list
    for eachline in fin:
        #fill up the word list and get rid of new lines
        wordList.append(eachline.strip())

    word_dict = {} # create a dictionary
    for eachWord in wordList:
        tuple = getLetters(eachWord) # make a tuple out of each word
        word_dict[tuple] = wordList #store it into a dictionary

    print word_dict #print out the dictionary


if __name__ == '__main__':
    main()

现在,虽然我可以将元组存储为字典键,但我不知道当且仅当单词列表具有这些键时,如何将单词列表存储为值。

例如: 如果在字典中如果有键 ('d', 'o', 'g'),我会得到该特定条目的值 god 和 dog,假设这两个单词在单词列表中(从words2.txt 文件。

【问题讨论】:

    标签: python dictionary tuples


    【解决方案1】:

    您正在存储 整个 词表。您想存储每个排序的字母元组的匹配词:

    word_dict = {} # create a dictionary
    
    for eachWord in wordList:
        key = getLetters(eachWord) # make a tuple out of each word
        if key in word_dict:
            word_dict[key].append(eachWord)
        else:
            word_dict[key] = [eachWord]
    

    如果键不存在,这将为给定键(字母元组)创建一个列表,否则只是附加单词。

    您可以使用collections.defaultdict 来简化此操作:

    from collections import defaultdict
    
    word_dict = defaultdict(list)
    
    for eachWord in wordList:
        word_dict[getLetters(eachWord)].append(eachWord)
    

    因为这样您就不需要每次都显式测试密钥。

    【讨论】:

    • 我做了这段代码,但它似乎把执行变成了一个无限循环。
    • @user1768884:那么你需要仔细检查你的代码;我的示例无法创建无限循环。
    猜你喜欢
    • 2011-02-07
    • 2016-03-18
    • 2012-01-01
    • 2010-10-28
    • 2013-01-11
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多