【问题标题】:How to create a dictionary out of a list?如何从列表中创建字典?
【发布时间】:2021-09-01 01:10:14
【问题描述】:

我从一个 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']

我的输出应该看起来像这样

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

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

提前致谢。

【问题讨论】:

标签: python list sorting dictionary tuples


【解决方案1】:
     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}

这就是你想要的

【讨论】:

    【解决方案2】:

    使用Counter:

    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)
    

    输出:

    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`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2018-11-06
      • 2020-03-07
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多