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



如何制作类似于字典的列表? 当我下面有文字时

科学家们希望面部识别可能有助于他们的 了解神经退行性疾病。

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

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

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

我不知道你为什么要在这里使用列表,字典会更容易制作和访问。更好的是,可以直接从这样的单词列表中构建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])

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

最新更新