Python 假设旁边的每一个数字都是它的值,那么如何表示列表中的字典呢?
我有一张这样的清单Python 假设旁边的每一个数字都是它的值,那么如何表示列表中的字典呢?,python,dictionary,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”用两个不同的值出现两次,因此我们将出现
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]
您可以使用“跨步”命令一次“跨步”阵列2个项目。范围中可选的第三个参数允许您定义“跳过”
范围(开始、停止[步进])
使用此方法,我们可以创建一系列索引,在整个列表长度内一次向前跳过2个索引。然后,我们可以询问列表该索引中的“名称”是什么,以及它后面的“值”是什么
new_dict = {}
for i in range(0, len(lista), 2):
name = lista[i]
value = lista[i + 1]
# the name already exists
# convert their values to numbers, add them, then convert back to a string
if name in new_dict:
new_dict[name] = str( int(new_dict[name]) + int(value) )
# the name doesn't exist
# simply append it with the value
else:
new_dict[name] = value
正如@Soviut所解释的,您可以使用步长值为2的
range()
函数直接访问word。正如我在列表中看到的,您的值存储为字符串,所以我将它们转换为整数
lista = ['hello','2','go','5','sit','4','line','3','sit','2', 'go','9','play','0']
data = {}
for i in range(0, len(lista), 2): # increase searching with step of 2 from 0 i.e. 0,2,4,...
if lista[i] in data.keys(): # this condition checks whether your element exist in dictionary key or not
data[lista[i]] = int(data[lista[i]]) + int(lista[i+1])
else:
data[lista[i]] = int(lista[i+1])
print(data)
输出
使用
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()
,以同步提取这些值。我们将这些项作为(键、值)
对分配给defaultdict
,它恰好保持计数
如果需要,请将整数转换为字符串:
{k: str(v) for k, v in dd.items()}
# {'go': '14', 'hello': '2', 'line': '3', 'play': '0', 'sit': '6'}
另一种工具可能是
计数器
(参见@DexJ的答案),它与这种类型的defaultdict
相关。实际上,Counter()
可以在此处替换defaultdict(int)
,并返回相同的结果。另一种解决方案使用iter()
、itertools.zip\u longest()
和itertools.groupby()
函数:
import itertools
lista = ['hello','2','go','5','sit','4','line','3','sit','2', 'go','9','play','0']
it = iter(lista)
d = {k: sum(int(_[1]) for _ in g)
for k,g in itertools.groupby(sorted(itertools.zip_longest(it, it)), key=lambda x: x[0])}
print(d)
输出:
{'line': 3, 'sit': 6, 'hello': 2, 'play': 0, 'go': 14}
输出:
{'hello': 2, 'go': 14, 'sit': 6, 'line': 3, 'play': 0}
您可以使用范围(开始、结束、步骤)获取端点和拆分列表,只需从集合中使用计数器()对重复键的值求和,即可:)
这里的yourdict将是{'go':14,'line':3,'sit':6,'play':0,'hello':2}
尝试使用
defaultdict
求和必须是字符串吗?'go':'5'
将替换为'go':'9'
,而不是'go':'14'
lista = ['hello','2','go','5','sit','4','line','3','sit','2', 'go','9','play','0']
dictionary = {}
for keyword, value in zip(*[iter(lista)]*2): # iterate two at a time
if keyword in dictionary: # if the key is present, add to the existing sum
dictionary[keyword] = dictionary[keyword] + int(value)
else: # if not present, set the value for the first time
dictionary[keyword] = int(value)
print(dictionary)
{'hello': 2, 'go': 14, 'sit': 6, 'line': 3, 'play': 0}
from collections import Counter
counter_obj = Counter()
lista = ['hello','2','go','5','sit','4','line','3','sit','2', 'go','9','play','0']
items, start = [], 0
for end in range(2,len(lista)+2,2):
print end
items.append(lista[start:end])
start = end
for item in items:
counter_obj[item[0]] += int(item[1])
yourdict = dict(counter_obj)
print yourdict