簡體   English   中英

我如何從列表中表示一個字典,假設它旁邊的其他所有數字都是它的值?

[英]How do I represent a dictionary from a list assuming that every other number by its side is its value?

我有一個看起來像這樣的清單,

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)並返回相同的結果。

您可以使用range()一次“跨越”數組2個項目。 范圍中的可選第3個參數使您可以定義“跳過”。

范圍(開始,停止[,步驟])

使用此功能,我們可以為整個列表長度創建一次一次跳過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

如@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}

使用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}
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}

您可以使用range(start,end,steps)來獲取端點和拆分列表,而只需使用Collection中的Counter()對重復鍵的值求和就可以了:)

此處yourdict將為{'go':14,'line':3,'sit':6,6,'play':0,'hello':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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM