I have a sentence called "myString" , What i am trying to do is that, creating a dictionary from the sentence where first character of the each word must be the key of the dictionary( white , w), and all words starting with that character must be the values of that keys.('w',['white','with']).
I have already written some python code. I want to know which code snippet is better or is there any better approach to this problem. Like a Dictionary Comprehension.?
我要生成的输出。
{'w': ['white', 'with', 'well'], 'h': ['hats', 'hackers', 'hackers', 'hackable', 'hacker', 'hired'] ...}
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={}
^{pr2}$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)
这应该适用于您的目的:
可以使用dict comprehension为counterDict指定默认值,然后附加:
如果您喜欢一行代码,并且迷恋于*
comprehensions
(像我一样),您可以将字典理解与 列表理解:相关问题 更多 >
编程相关推荐