簡體   English   中英

如何從列表中創建字典?

[英]How to create a dictionary out of a list?

我從 word 文檔中提取了一個數字列表,以查看一天中的哪個小時給我們的訪問次數最多。 我想從數字列表中創建一個鍵號對字典。

這些是我的數字列表

['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']

我的 output 應該看起來像這樣

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

我不太清楚下一步該做什么。

提前致謝。

使用計數器

from collections import Counter

l = ['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10',
     '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']
result = Counter(l)

OUTPUT:

Counter({'09': 2,
         '18': 1,
         '16': 4,
         '15': 2,
         '14': 1,
         '11': 6,
         '10': 3,
         '07': 1,
         '06': 1,
         '04': 3,
         '19': 1,
         '17': 2})

要獲得most common的元素,您可以使用:

most_common_element = result.most_common(1)[0] # prints `11`
     z = ['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']
        # trans list to dict
        d = dict((int(i), z.count(i)) for i in z)
        # sort dict by key
        d = dict(sorted(d.items()))
        print(d)
        OUTPUT:
 {4: 3,
     6: 1,
     7: 1,
     9: 2,
     10: 3,
     11: 6,
     14: 1,
     15: 2,
     16: 4,
     17: 2,
     18: 1,
     19: 1}

這就是你想要的

暫無
暫無

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

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