Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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 3.x 返回包含单词首字母的键以及这些单词列表的词典?_Python 3.x_Loops - Fatal编程技术网

Python 3.x 返回包含单词首字母的键以及这些单词列表的词典?

Python 3.x 返回包含单词首字母的键以及这些单词列表的词典?,python-3.x,loops,Python 3.x,Loops,我想写一个函数,它接受一个单词和键的列表,并将这些键作为字典键输出,其中包含以该字母开头的任何单词。 如何使用简单的Python3代码实现这一点 例如,采取(['apples','apple','bananna','fan','fad') 返回{'a':['apple','apples'],'f':['fan']} 到目前为止,我已经尝试: def dictionary(words, char_keys) char_keys = remove_duplicates(char_keys) ret

我想写一个函数,它接受一个单词和键的列表,并将这些键作为字典键输出,其中包含以该字母开头的任何单词。 如何使用简单的Python3代码实现这一点

例如,采取
(['apples','apple','bananna','fan','fad')

返回
{'a':['apple','apples'],'f':['fan']}

到目前为止,我已经尝试:

def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
    if word[0] in char_keys and word[0] not in keys_in_dict:   
        ret[word[0]] = word
        keys_in_dict.append(word[0])
    elif word[0] in keys_in_dict:
        ret[word[0]] += (word)
return ret

这提供了一种正确的输出,但它的输出是在单个字符串中,而不是字符串列表中。(我知道def没有正确缩进)

不确定输入列表是否仅由字符串组成,或者它还可以包括字符串的子列表(我也不确定为什么“fad”在您的示例中消失)。显然,在后一种情况下,它需要更多的努力。为了简单起见,我假设if只包含字符串,下面是一段代码,希望能指明方向:

d = {}
for elem in input_list[0]:
    if elem[0] in input_list[1]
        lst = d.get(elem[0], [])
        lst.append(elem)
        d[elem] = lst

如果输入是字符串列表,则可以检查dict中是否有字符,如果是,则添加单词,否则添加带有单词的列表:

def dictionary(inpt):
    result = {}
    for word in inpt:
        char = word[0]
        if char in result:
            result[char].append(word)
        else:
            result[char] = [word]
    return result
实现这一点的现代方法是使用with
list
作为参数

def dictionary(inpt):
    result = defaultdict(list)
    for word in inpt:
        result[word[0]].append(word)
    return result

尝试用代码解决此练习。请澄清输入是否只能是列表或包含列表和字符串的iterable。f、a和d是字典键。因为我没有文字可供分配,所以我真的不想把它放在那里。我将发布我现在拥有的。我的错,没有仔细阅读你的文章。查看修改后的代码-您只需测试elem[0]是否在您的密钥列表中。