使用.get()方法将列表中的元素添加到字典中



我有一个元素列表[1, 2, 5, 2, 3, 7, 5, 8]。我想把它放入字典中,所以它会是"key : how many times it appears in the list",所以字典看起来像这样:

{"1:1", "2:2", "5:2", "3:1", "7:1", "8:1"}

该解决方案应适用于任何列表。

我做了列表的迭代,但是在将元素添加到字典中时收到一个错误。

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
midwayDict = midwayDict.get(element, 0)
print(midwayDict)

它给我的是" AttributeError: 'int' object has no attribute 'get' "。我使用的方法有问题吗?还是我应该用另一种方式?

我看到这个在某个地方使用了一段时间,但我无法找到在哪里以及如何准确地做到这一点。

您的代码中的错误是

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
midwayDict = midwayDict.get(element, 0)  # <- you are assigning 0 to dict so in next iteration you are accessing .get method on integer so its saying there is no get method on int object
print(midwayDict)

应该

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
_ = midwayDict.setdefault(element, 0)
midwayDict[element] += 1
print(midwayDict)

from collections import Counter
given = (1, 2, 5, 2, 3, 7, 5, 8)
print(Counter(given))

你的代码中只有一个错误。

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in set(given):
midwayDict[element] = midwayDict.get(element, 0)+1 # edited
print(midwayDict)

更好的方法是使用字典推导式。

given = (1, 2, 5, 2, 3, 7, 5, 8)
d = {a:given.count(a) for a in set(given)}
print(d)

相关内容

  • 没有找到相关文章

最新更新