我有一句名为“myString”的句子,我想要做的是, 从句子的第一个字符创建字典 每个单词必须是字典的键(白色,w)和所有单词 从该角色开始必须是该值的值 密钥。( 'W',[ '白色', '与'])。
我已经编写了一些python代码。我想知道哪个代码 片段更好还是有更好的方法解决这个问题。 像字典理解一样。?
我希望生成输出。
{'w':['white','with','well'],'h':['hats','hackers','hackers', 'hackable','hacker','雇用'] ......}
myString = "White hats are hackers employed with the efforts of
keeping data safe from other hackers by looking for loopholes and
hackable areas This type of hacker typically gets paid quite well and
receives no jail time due to the consent of the company that hired
them"
counterDict = {}
for word in myString.lower().split():
fChar = word[0]
if fChar not in counterDict:
counterDict[fChar] = []
counterDict[fChar].append(word)
print(counterDict)
for word in myString.lower().split():
fChar = word[0]
counterDict.get(word,[]).append(word)
print(counterDict)
import collections
counterDict = collections.defaultdict(list)
for word in myString.lower().split():
fChar = word[0]
counterDict[fChar].append(word)
print(counterDict)
import collections
counterDict = collections.defaultdict(list)
[ counterDict[word[0]].append(word) for word in myString.lower().split() ]
print(counterDict)
答案 0 :(得分:1)
您可以使用dict comprehension为counterDict分配默认值,然后追加:
myString = "White hats are hackers employed with the efforts of
keeping data safe from other hackers by looking for loopholes and
hackable areas This type of hacker typically gets paid quite well and
receives no jail time due to the consent of the company that hired
them"
new_string = myString.split()
counterDict = {i[0].lower():[] for i in new_string}
for i in new_string:
counterDict[i[0].lower()].append(i)
答案 1 :(得分:0)
这应该适用于您的目的:
from collections import defaultdict
counter_dict = defaultdict(list)
word_list = [(word[0], word) for word in my_string.lower().split()] #index 0 and the word is taken
for letter, word in word_list:
counter_dict[letter].append(word)
答案 2 :(得分:0)
如果你喜欢单行并且迷恋* comprehensions
(和我一样),你可以将词典理解与
列表理解:
new_string = myString.lower().split() #helps readability
counterDict = {i[0]:[z for z in new_string if z[0] == i[0]] for i in new_string}