【问题标题】:Populating dictionary with list if statement用列表 if 语句填充字典
【发布时间】:2018-03-27 09:52:40
【问题描述】:

我不明白字典“count”是如何被“List”填充和引用的。

具体来说,为什么使用“if item in count”语句将列表('List')中的项目添加到字典('count')中?

'count' 字典一开始是空的,并且没有'append' 函数。

这里是python函数:

def countDuplicates(List):
    count = {}
    for item in List:
        if item in count:
            count[item] += 1
        else:
            count[item] = 1
    return count

print(countDuplicates([1, 2, 4, 3, 2, 2, 5]))

输出:{1: 1, 2: 3, 3: 1, 4: 1, 5: 1}

【问题讨论】:

  • 这段代码有问题吗?这是你的代码吗?
  • 欢迎来到 SO。请花时间阅读How to Ask 及其包含的链接。您可能还想花一些时间通过the Tutorial 工作。
  • 我认为问题很明确。第二段询问in 做了什么,第三段询问如何在没有append 的情况下向dict 添加内容。
  • Python 有内置的collections.Counter() 来完成同样的任务

标签: python list function dictionary


【解决方案1】:

您可以手动运行您的代码,看看它是如何工作的

count = {} // empty dict

遍历列表的第一个元素是 1 它检查这一行中的 dict 以查看该元素是否在之前添加到 dict

if item in count:

它不在计数中,因此它将元素放入列表中并在这一行中使其值为 1

 count[item] = 1 //This appends the item to the dict as a key and puts value of 1

计数变为

count ={{1:1}}

然后它遍历下一个元素,女巫是 2 个相同的故事计数变为

count={{1:1},{2:1}}

下一项是 4

count = {{1:1},{2:1},{4,1}}

在这种情况下,下一项是 2,我们的 dict 中有 2,因此在这一行中它的值增加了 1

     count[item] += 1

计数变为

count = {{1:1},{2:2},{4,1}}

它会一直持续到列表完成

【讨论】:

  • 感谢@Alper First Kaya!这正是我正在寻找的解释/演练!
  • 我想告诉你的是,你并不孤单:P from collections import Counter; duplicates = Counter([1, 2, 4, 3, 2, 2, 5]) docs.python.org/2/library/collections.html#collections.Counter
  • 谢谢@slackmart。在这种情况下,“收藏”库肯定也可以工作。我发布了这个问题,以了解使用 if 语句将列表中的项目分配到字典中。绝对基础,但值得一课。
【解决方案2】:

这就是它检查if item in count 的原因,如果这是您第一次看到计数,它将失败(因为它还没有在字典中定义)。

在这种情况下,它将使用count[item] = 1 定义它。

下次看到计数时,它已经被定义(为 1),因此您可以使用count[item] += 1 递增它,即count[item] = count[item] + 1,即count[item] = 1 + 1 等。

【讨论】:

  • 谢谢!现在它是有道理的! “if item in count”将第一次失败,并在第一次遇到 List 中的唯一项目时将 List 中的“item”分配给 [count]。 >
【解决方案3】:

具体来说,为什么使用“if item in count”语句将列表('List')中的项目添加到字典('count')中?


`checking if the element already added in to dictionary, if existing increment the value associated with item.
Example:
[1,2,4,3,2,2,5]
dict[item]  = 1  value is '1'--> Else block, key '1'(item) is not there in the dict, add to and increment the occurrence by '1'

when the element in list[1,2,4,3,2,2,5] is already present in the dict count[item] += 1 --> increment the occurrence against each item`

==================

'count' 字典一开始是空的,并且没有'append' 功能。

空字典不支持附加功能,可以通过 计数[项目] += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2018-07-06
    相关资源
    最近更新 更多