从第一个字符是关键字,单词是值的句子创建词典

2024-06-26 12:39:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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}$

使用字典.get方法

for word in myString.lower().split():
  fChar = word[0]
  counterDict.get(word,[]).append(word)
print(counterDict)  

在集合.defaultdict()

import collections
counterDict = collections.defaultdict(list)
for word in myString.lower().split():
  fChar = word[0]
  counterDict[fChar].append(word)
print(counterDict)

在集合.defaultdict()+列表理解

import collections
counterDict = collections.defaultdict(list)
[ counterDict[word[0]].append(word) for word in myString.lower().split() ]
print(counterDict)

Tags: andofthetoforthatiswith
3条回答

这应该适用于您的目的:

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)

可以使用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)

如果您喜欢一行代码,并且迷恋于*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}

相关问题 更多 >