像字典一样在列表中存储键和值?

2024-10-16 20:46:54 发布

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

我怎样才能列一个类似字典的清单? 当我有一个文本下面

The scientists hope facial recognition may help with their understanding of neurodegenerative diseases.

我想列一份通讯组名单。例如在这种情况下,每个单词出现一次,那么我认为列表应该是

[(('the'), 1),
(('scientists'), 1), 
(('hope'), 1),........]

我还假设根据这些列表制作分布图。 在这种情况下还有其他更好的办法吗? 如果您能详细解释,我们将不胜感激。你知道吗


Tags: ofthe文本列表字典withhelp情况
1条回答
网友
1楼 · 发布于 2024-10-16 20:46:54

我不知道为什么你会想在这里使用一个列表,一本字典会更容易制作和访问。更好的是,一个collections.Counter可以直接从这样的单词列表中构建:

from collections import Counter

words = ["the", "scientists", ...]

word_counter = Counter(words) # a subclass of dict

# word_list = list(word_counter.items()) # this would convert it to a list of tuples

如果需要保持顺序,可以在列表中使用索引字典:

words = ["the", "scientists", ...]

counts = []
indices = {}
for word in words:
  if word in indices:
    counts[word][1] += 1
  else:
    indices[word] = len(counts)
    counts.append([word, 1])

您也可以在列表中搜索正确的索引,但这样更快。你知道吗

相关问题 更多 >