简体   繁体   English

通过放入字典来计算列表中的值

[英]Counting values in list by putting in dictionary

alist = [5, 7, 6, 2, 9, 1, 7]

D = {}

for each unique number in list, set a new key for each key in dictionary, count number of that key and set to value对于列表中的每个唯一数字,为字典中的每个键设置一个新键,计算该键的数量并设置为值

this should look like {5:1, 2:1, 6:1, 9:1, 1:1, 7:2}这应该看起来像{5:1, 2:1, 6:1, 9:1, 1:1, 7:2}

algorithm:算法:

For each number n on the input list:
∗ If n in count: set count[n] to count[n] + 1
∗ else: set count[n] to 1

I don't know how to go about this.我不知道该怎么做。 Can anybody show me how?有人可以告诉我怎么做吗?

Attempt:试图:

for number in alist:
    if number in D:
        D[number] = D[number]+1
    else:
        D[number] = 1

Error:错误:

Traceback (most recent call last): File "<pyshell#15>", line 3, in
<module> D[number] = D[number]+1 KeyError: 5
>>> from collections import Counter
>>> Counter(alist)
Counter({7: 2, 1: 1, 2: 1, 5: 1, 6: 1, 9: 1})

Simplest way to do this is a dictionary comprehension最简单的方法是字典理解

count_dict = {elem:a_list.count(elem) for elem in a_list}

It's like a for loop but it specifies both the key and value for each dictionary item.它就像一个 for 循环,但它指定了每个字典项的键和值。

Ayush Shanker's answer is a perfectly valid way to do what you want. Ayush Shanker 的回答是一种完全有效的方式来做你想做的事。 I'll point out how to fix the code you have now.我将指出如何修复您现在拥有的代码。

First, in these two lines首先,在这两行中

for number in alist:
    if number in alist:

You're basically saying "for every number in alist, check to see if it's in alist".您基本上是在说“对于 alist 中的每个数字,请检查它是否在 alist 中”。 Of course it is!当然是这样! So, you really want if number in D: for the second line, because then you're checking to see if the number is in the dictionary you're building.所以,你真的想要if number in D:对于第二行,因为你正在检查这个数字是否在你正在构建的字典中。

The second problem is this:第二个问题是这样的:

        D[number] = D[number+1]

number and number+1 here are indices, so you're referring to two different elements in D .这里的numbernumber+1是索引,因此您指的是D两个不同元素。 The solution is to move the +1 outside.解决方案是将+1移到外面。 This is what the fixed code looks like:这是固定代码的样子:

for number in alist:
    if number in D:
        D[number] = D[number] + 1
    else:
        D[number] = 1

To be more Pythonic, you can also replace D[number] = D[number] + 1 with D[number] += 1 .为了更加 Pythonic,您还可以将D[number] = D[number] + 1替换为D[number] += 1

To fix you code and algorithm, you need to check if n is in D.keys() (which returns list of keys of D dictionary:要修复您的代码和算法,您需要检查n是否在D.keys() (它返回D字典的键列表:

>>> D = {}
>>> for n in alist:
    if n in D.keys():
        D[n] += 1
    else:
        D[n] = 1


>>> D
{1: 1, 2: 1, 5: 1, 6: 1, 7: 2, 9: 1}

SOLUTION:解决方案:

 def mode(somelist):
        count = {}
        for n in alist:
            if n in count:
                count[n]+=1
            else:
                count[n] = 1
        return(count)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM