简体   繁体   English

使用字典计算用空格分隔的列表中数字的出现

[英]Counting occurences of number in a list separated by spaces using dictionaries

If I have a list of numbers (ex:- 1 2 3 3 2 2 2 1 3 4 5 3 ) how can I use dictionaries in python to count the occurrences of each number in the list? 如果我有一个数字列表(例如: 1 2 3 3 2 2 2 1 3 4 5 3 ),如何在python中使用字典来计算列表中每个数字的出现次数? So the output be something like: 所以输出是这样的:

Enter numbers separated by spaces : 1 2 3 3 2 2 2 1 3 4 5 3 输入以空格分隔的数字: 1 2 3 3 2 2 2 1 3 4 5 3

{'1': 2, '3': 4, '2': 4, '5': 1, '4': 1}

1 occurs 2 times

3 occurs 4 times

2 occurs 4 times

5 occurs one time

4 occurs one time 

Also if a number occurs only once the output should be "one time". 同样,如果一个数字仅出现一次,则输出应为“一次”。

This is what I have so far: 这是我到目前为止的内容:

numbers=input("Enter numbers separated by spaces:-")
count={}
for number in numbers:
    if number in count:
        count[number] = count[number]+1
    else:
        count[number] = 1

print(number)

but my output ends up being the last number, i, input can someone help me? 但是我的输出最终是最后一个数字,我,有人可以帮助我吗?

OK, this is what I have now: 好的,这就是我现在所拥有的:

numbers = input("Enter numbers separated by spaces:-") # i.e. '1 2 3 3 2 2 2 1 3 4 5 3'
my_list = list(map(int, numbers.strip().split(' ')))
count = {}
for x in set(my_list):
   count[x] = my_list.count(x)
print(count)
for key, value in count.items():
    if value == 1:
         print('{} occurs one time'.format(key))
    else:
         print('{} occurs {} times'.format(key, value))

This is what I have now and it seems pretty good, if theres any way to make it better please do let me know. 这就是我现在所拥有的,而且看起来还不错,如果有什么方法可以使它更好,请告诉我。 Thanks a lot everybody 非常感谢大家

You're close -- you want print(count) , not print(number) so that you're printing the dictionary. 您接近了-您想要print(count)而不是print(number)以便打印字典。

Incidentally, you can use the Counter class from the collections library to do this for you: 顺便说一句,您可以使用collections库中的Counter类为您完成此操作:

>>> import collections
>>> numbers = input("Enter numbers ").split(' ')
>>> count = Counter(numbers)
>>> print(count)

The set() method returns a list of unique values in an iterable, and the count() method returns the number of occurrences of a particular number a list. set()方法返回可迭代的唯一值列表,而count()方法返回列表中特定数字的出现次数。

Using these facts, you can solve the problem by doing something like below. 利用这些事实,您可以通过执行以下操作来解决问题。

numbers = input("Enter numbers seperated by spaces:-") # i.e. '1 2 3 3 2 2 2 1 3 4 5 3'
my_list = list(map(int, numbers.strip().split(' ')))
count = {}
for x in set(my_list):
    count[x] = my_list.count(x)

for key, value in count.items():
    if value == 1:
        print('{} occurs one time'.format(key))
    else:
        print('{} occurs {} times'.format(key, value))

Try counters: 尝试柜台:

>>> import collections
>>> number_string = '1 2 3 3 2 2 2 1 3 4 5 3'
>>> number_list = number_string.split(' ') # provide a list split on the spaces
>>> counts = collections.Counter(number_list)
>>> counts
Counter({'2': 4, '3': 4, '1': 2, '4': 1, '5': 1})

You can also count as you go: 您还可以随身携带计数:

>>> counts = collections.Counter()
>>> for l in "GATTACA":
...     counts[l] +=1
... 
>>> counts
Counter({'A': 3, 'T': 2, 'C': 1, 'G': 1})

To print this nicely: 要很好地打印:

import collections

def print_counts_in_spaced_string(number_string):
    number_list = number_string.split(' ') # provide a list split on the spaces
    counts = collections.Counter(number_list)
    for key, value in counts.items():
        format_string = '{key} occurs {value} {times}'
        if value == 1:
            value, times = 'one', 'time'
        else:
            times = 'times'
        print(format_string.format(key=key, value=value, times=times))

number_string = '1 2 3 3 2 2 2 1 3 4 5 3'
print_counts_in_spaced_string(number_string)

Which prints: 哪些打印:

1 occurs 2 times
2 occurs 4 times
3 occurs 4 times
4 occurs one time
5 occurs one time

Your problem is that you start off with an empty dict . 您的问题是您从空dict This means that your check if number in count will always fail (since count is an empty dictionary). 这意味着您检查if number in count是否总会失败(因为count是一个空字典)。

I would recommend using collections.Counter as others have suggested. 我建议使用collections.Counter就像其他人建议的那样。 But if you're really looking to debug your code, then here's what I would do: 但是,如果您真的要调试代码,那么这就是我要做的:

numbers=input("Enter numbers seperated by spaces:-")
count={}
for number in numbers.split(): # ignore all the white-spaces
  if number not in count:
    count[number] = 0
  count[number] += 1
for num,freq in count.items():
  print(num, "occurs", freq, "times")

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

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