簡體   English   中英

嘗試從數字列表創建字典,但列表索引超出范圍

[英]Trying to create a dictionary from a list of numbers, but list index is out of range

我正在嘗試創建一個函數來創建一個字典,其中出現的次數是鍵,每個鍵都有一個作為值出現多次的數字列表

它搞砸的部分是在線:

if num_list[i] not in num_dic.values():

或者也搞砸了:

if num_list.index(i) == num_list.index(j):

下面的函數從 num_list 創建一個字典

def createDic(num_list):
    num_dic = {}
    num_occurs = 0
    for i in num_list:
        if num_list[i] not in num_dic.values():
            for j in num_list:
                if num_list.index(i) == num_list.index(j):
                    num_occurs += 1
            num_dic[num_occurs].append(num_list[i])
        num_occurs = 0
    return num_dic

您應該以不同的方式執行此操作,首先計算出現次數,然后將其轉換為字典:

>>> a = [1,1,2,3,4,4,4]
>>> from collections import Counter, defaultdict
>>> c = Counter(a)
>>> c
Counter({4: 3, 1: 2, 2: 1, 3: 1})
>>> occurences = defaultdict(list)
>>> for a,b in c.items() :
...     occurences[b].append(a)
... 
>>> occurences
defaultdict(<type 'list'>, {1: [2, 3], 2: [1], 3: [4]})
>>> dict(occurences)
{1: [2, 3], 2: [1], 3: [4]}
data = ["a", "b", "b", "c", "c", "c", "d", "d", "d"]
info = {}

for i in data:
    count = data.count(i)

    if count not in info:
        info[count] = [i]
    elif i not in info[count]:
        info[count].extend(i)

print(info)

輸出:

{1: ['a'], 2: ['b'], 3: ['c', 'd']}

更好的解決方案,但使用導入:

from collections import Counter

data = ["a", "b", "b", "c", "c", "c", "d", "d", "d"]
info = {}

for o, c in Counter(data).items():
    info[c] = [o] if c not in info else info[c] + [o]

print(info)

輸出:

{1: ['a'], 2: ['b'], 3: ['c', 'd']}
  1. 這是一個低效的實現,它是 O(n^2),你可以在 O(n) 中解決它
  2. 您沒有初始化num_dict ,您可以使用 defaultdict:

    num_dict = defaultdict(列表)

  3. num_list[i]不會在num_dict.values()因為values()是列表而num_list[i]是一個整數(你假設)

  4. 你用i迭代列表,但然后認為它是索引而不是列表中的值,你應該用for i in range(len(num_list))替換它(j 相同)

暫無
暫無

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

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