2017-08-30 60 views
2

我有一个列表看起来像这样,如何从列表中表示字典,假设其旁边的每个其他数字都是其值?

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

在列表“去”与两个不同的值中出现了两次,所以我们刚才添加单词后出现的号码,同样,对于换句话说。 这是我的方法,它似乎不工作。

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] 
+0

尝试'defaultdict ' – pylang

+1

重要吗?这些款项是字符串? – pylang

回答

1

可以“跨越”数组2项在同一时间使用range()。范围中的可选第三个参数可让您定义“跳过”。

范围(启动,停止[,步])

利用这一点,我们可以创建一个范围,在一次跳到2,为您的列表的整个长度指标。然后,我们可以询问清单在该索引lista[i]处的“名称”以及它后面的“价值”lista[i + 1]

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 
+1

''go':'5''将被替换为''go':'9''而不是''go':'14''在你的案例中 – Gahan

+0

@Gahan我已经更新了答案以进行添加 – Soviut

0

通过@Soviut说明你可以使用range()功能与步长值2直接到达至字。正如我在你的列表中看到的,你将值存储为字符串,所以我已将它们转换为整数。

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) 

输出
{'hello': 2, 'go': 14, 'sit': 6, 'line': 3, 'play': 0} 
2

唯一密钥的计数出现通常是可能的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)并返回相同的结果。

0

使用iter()itertools.zip_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} 
0
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} 
0

您可以使用范围(开始,结束,步)从收藏获取端点和分裂列表,只是使用计数器()总结重复键的值就大功告成了:)

这里yourdict将{ '去':14, '行':3, '坐':6, '玩':0, '你好':2}

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 
相关问题