首页 > 解决方案 > Python:有没有办法只使用计数变量并附加一个空列表来计算列表中数字的频率?

问题描述

我想把代码分成两部分:首先,编写一个代码来创建唯一的数字数组。其次,为每个数字的频率编写代码。对应我的思考过程的示例代码:

input_array = [3, 6, 8, 2, 4, 8, 3, 1, 8, 9, 7, 0, 5, 5, 1]
#expected_output = {'0': 1, '1': 2, '3': 2, etc.}

unique_numbers = []
frequency_array = []

#Write a code to create the unique number array
#Write a code for the frequency of each number

for inp in input_array:
    if inp not in unique_numbers:
        unique_numbers.append(inp) #Appends unique numbers to unique number array

#I thought that the following code would be able to iterate through the input array for each number in the unique number list
for un in unique_numbers:
    i = 0
    for inp in input_array:
        counter = input_array.count(unique_numbers[i]) #Count frequency
        frequency_array.append(counter) #Add count to frequency array
        counter = 0 #Return counter to 0
        i += 1 #Change i value to i+1

print('{}:{}'.format(unique_numbers, frequency_array))

但我收到错误“列表索引超出范围”。我查了一下,似乎与列表“input_array”和“unique_numbers”的长度不同有关,因此我不能在另一个之上使用for循环吗?

有人可以帮助我了解我哪里出错了吗?我刚刚开始学习和使用python。任何帮助都感激不尽。谢谢!

标签: pythonpython-3.xliststatistics

解决方案


如果您不想使用库,为什么不只是:

dict = {}
for i in input_array:
    if i in dict.keys():
        dict[i] += 1
    else:
        dict[i] = 1

推荐阅读