【问题标题】:Python: Convert this list into dictionaryPython:将此列表转换为字典
【发布时间】:2010-10-18 02:10:07
【问题描述】:

我有个问题,不知道怎么用python写代码。

我有一个list[10, 10, 10, 20, 20, 20, 30]

我希望它出现在这样的字典中

{"10": 1, "20":  3, "30" : 1}

我怎样才能做到这一点?

【问题讨论】:

  • 如果您计算该列表中的项目数,那不就是{"10": 3, "20":3, "30":1}吗?如果没有,这本词典是如何编译的?与它们的键相关的值是什么?
  • defaultdict 解决所有问题

标签: python list dictionary formatting


【解决方案1】:
from collections import Counter
a = [10, 10, 10, 20, 20, 20, 30]
c = Counter(a)
# Counter({10: 3, 20: 3, 30: 1})

如果你真的想将键转换为字符串,那是一个单独的步骤:

dict((str(k), v) for k, v in c.iteritems())

这个类是 Python 2.7 的新类;对于早期版本,请使用此实现:

http://code.activestate.com/recipes/576611/


编辑:将其删除,因为 SO 不允许我将代码粘贴到 cmets 中,

from collections import defaultdict
def count(it):
    d = defaultdict(int)
    for j in it:
        d[j] += 1
    return d

【讨论】:

    【解决方案2】:

    另一种不使用setCounter的方式:

    d = {}
    x = [10, 10, 10, 20, 20, 20, 30]
    for j in x:
        d[j] = d.get(j,0) + 1
    

    编辑:对于包含 100 个唯一项目的大小为 1000000 的列表,此方法在我的笔记本电脑上运行 0.37 秒,而使用 set 的答案需要 2.59 秒。仅针对 10 个独特的项目,前一种方法需要 0.36 秒,而后一种方法只需要 0.25 秒。

    编辑:使用 defaultdict 的方法在我的笔记本电脑上需要 0.18 秒。

    【讨论】:

    • 如果这是一场性能竞赛,请检查我在答案中输入的 defaultdict 版本(责备 SO 不让我将其粘贴在这里),它的速度大约是原来的两倍。
    • 感谢您的评论。你完全正确:你的方法在我的笔记本电脑上运行了 0.18 秒。
    【解决方案3】:

    这样

    l = [10, 10, 10, 20, 20, 20, 30]
    uniqes = set(l)
    answer = {}
    for i in uniques:
        answer[i] = l.count(i)
    

    answer 现在是您想要的字典

    希望对你有帮助

    【讨论】:

      【解决方案4】:

      在 Python >= 2.7 中,您可以使用 dict 推导式,例如:

      >>> l = [10, 10, 10, 20, 20, 20, 30]
      >>> {x: l.count(x) for x in l}
      {10: 3, 20: 3, 30: 1}
      

      不是最快的方法,但非常适合小列表

      更新

      或者,受inspectorG4dget的启发,这更好:

      {x: l.count(x) for x in set(l)}
      

      【讨论】:

        猜你喜欢
        • 2015-07-23
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 2015-11-14
        • 2016-10-25
        • 2022-12-04
        • 2020-12-08
        • 1970-01-01
        相关资源
        最近更新 更多