【发布时间】:2017-05-23 16:52:48
【问题描述】:
我有一个叫做“myString”的句子,我想做的是, 从句子的第一个字符创建字典 每个单词必须是字典的键(白色,w),并且所有单词 以该字符开头的必须是该字符的值 键。('w',['white','with'])。
我已经写了一些python代码。我想知道哪个代码 sn-p 更好,或者有没有更好的方法来解决这个问题。 像字典理解一样。?
我想生成的输出。
{'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 = {}
for word in myString.lower().split():
fChar = word[0]
if fChar not in counterDict:
counterDict[fChar] = []
counterDict[fChar].append(word)
print(counterDict)
使用dictionary.get方法
for word in myString.lower().split():
fChar = word[0]
counterDict.get(word,[]).append(word)
print(counterDict)
collections.defaultdict()
import collections
counterDict = collections.defaultdict(list)
for word in myString.lower().split():
fChar = word[0]
counterDict[fChar].append(word)
print(counterDict)
collections.defaultdict( ) + 列表理解。
import collections
counterDict = collections.defaultdict(list)
[ counterDict[word[0]].append(word) for word in myString.lower().split() ]
print(counterDict)
【问题讨论】:
-
工作代码的改进属于 CodeReview.StackExchange.com
-
感谢您的回复。有什么方法可以使用字典理解来实现结果。?
-
您标记为
collections.Counter的解决方案没有使用 collections.Counter,他们使用的是 collections.defaultdict。抛开语义不谈,我的观点是 defaultdict(没有 list comp)是最好的方法。 -
这是一个错字,我已经编辑了帖子。
标签: python string list python-3.x dictionary