python - 假设列表旁边的所有其他数字都是其值,如何表示列表中的字典?

标签 python dictionary

我有一个看起来像这样的列表,

lista = ['hello','2','go','5','sit','4','line','3','sit','2', 'go','9','play','0']

在此列表中,单词后面的每个数字代表该单词的值。我想在字典中表示这个列表,以便添加每个重复单词的值。我希望字典是这样的:

dict = {'hello':'2', 'go':'14', 'sit':'6','line':'3','play':'0'}

在列表中,“go”出现了两次,具有两个不同的值,因此我们添加紧随该单词之后出现的数字,其他单词类似。 这是我的方法,貌似行不通。

import csv
with open('teest.txt', 'rb') as input:
    count = {}
    my_file = input.read()
    listt = my_file.split()
    i = i + 2
    for i in range(len(listt)-1):
        if listt[i] in count:
            count[listt[i]] = count[listt[i]] + listt[i+1]
        else:
            count[listt[i]] = listt[i+1]

最佳答案

通常可以使用 defaultdict 来计算唯一键的出现次数。

import collections as ct 

lista = ['hello','2','go','5','sit','4','line','3','sit','2', 'go','9','play','0']
dd = ct.defaultdict(int)
iterable = iter(lista)

for word in iterable:
    dd[word] += int(next(iterable)) 

dd
# defaultdict(int, {'go': 14, 'hello': 2, 'line': 3, 'play': 0, 'sit': 6})

这里我们初始化 defaultdict 以接受整数。我们创建一个列表迭代器,既创建一个生成器,又允许我们对其调用 next() 。由于单词和值在列表中连续成对出现,因此我们将迭代并立即调用 next() 来同步提取这些值。我们将这些项目作为 (key, value) 对分配给 defaultdict,后者恰好可以保持计数。

如果需要,将整数转换为字符串:

{k: str(v) for k, v in dd.items()}
# {'go': '14', 'hello': '2', 'line': '3', 'play': '0', 'sit': '6'}

替代工具可能是Counter(请参阅@DexJ的答案),它与这种类型的defaultdict相关。事实上,Counter() 可以在这里替换 defaultdict(int) 并返回相同的结果。

关于python - 假设列表旁边的所有其他数字都是其值,如何表示列表中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45952283/

相关文章:

java - 3 维列表或 map

python - Polyfill算法中如何处理水平方向?

python - 从 FTP 检索文件时如何指定本地目标文件夹

c++ - boost 函数映射到字符串

ios - Swift 2 - 使用从 A 到 Z 的键将数组分成字典

python - 使用map和setattr函数动态设置对象属性

Python 按键值排序字典

python - Jupyter 笔记本 rpy2 Rmagics : How to set the default plot size?

python - numpy 函数的省时组合

python - 如何使用 python 3.x 从远程 url 打印 csv 内容?