【问题标题】:Counting occurences of number in a list separated by spaces using dictionaries使用字典计算以空格分隔的列表中数字的出现次数
【发布时间】:2013-11-14 23:24:29
【问题描述】:

如果我有一个数字列表(例如:- 1 2 3 3 2 2 2 1 3 4 5 3 ),我如何使用 python 中的字典来计算列表中每个数字的出现次数? 所以输出是这样的:

输入以空格分隔的数字: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 

如果一个数字只出现一次,输出应该是“一次”。

这是我目前所拥有的:

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)

但我的输出最终是最后一个数字,我输入有人可以帮助我吗?

好的,这就是我现在拥有的:

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))

这就是我现在拥有的,看起来还不错,如果有任何改进的方法,请告诉我。非常感谢大家

【问题讨论】:

  • 计数器未定义是我得到的

标签: python dictionary counter


【解决方案1】:

你已经接近了——你想要print(count),而不是print(number),这样你就可以打印字典了。

顺便说一句,您可以使用 collections 库中的 Counter 类为您执行此操作:

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

【讨论】:

  • 我怎样才能得到我在问题中显示的输出
【解决方案2】:

set() 方法返回一个可迭代对象中唯一值的列表,count() 方法返回一个列表中特定数字的出现次数。

使用这些事实,您可以通过执行以下操作来解决问题。

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))

【讨论】:

  • 我试过了,但这是我得到的 builtins.AttributeError: 'map' object has no attribute 'count'
  • 好的,我猜你正在使用 Python 3.x。试试看:my_list = list(map(int, numbers.split(' ')))
  • 我没有输出,什么都没有发生
  • 你最后print(count)了吗?另外,尝试将 .strip() 方法添加到数字字符串(请参阅我更新的答案)。这将删除任何前导或尾随空格。我刚刚运行了这段代码,它按预期工作。
  • 这比我想象的要复杂得多
【解决方案3】:

尝试计数器:

>>> 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})

你也可以边走边算:

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

要打印得很好:

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)

哪些打印:

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

【讨论】:

    【解决方案4】:

    您的问题是您从一个空的dict 开始。这意味着您的检查 if number in count 将始终失败(因为 count 是一个空字典)。

    我建议像其他人建议的那样使用collections.Counter。但如果你真的想调试你的代码,那么我会这样做:

    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")
    

    【讨论】:

    • 使用此代码我的输出最终成为重复循环示例输入为 1 2 3 2 输出为:-1 发生 1 次 2 发生 1 次 1 发生 1 次 2 发生 1 次 3 发生 1 次1 发生 1 次 2 发生 2 次 3 发生 1 次 1 发生 1 次
    • @user2994135:很抱歉——我把代码缩进和格式缩进弄混了。现已修复!
    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多