python - 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。任何帮助都感激不尽。谢谢!
解决方案
如果您不想使用库,为什么不只是:
dict = {}
for i in input_array:
if i in dict.keys():
dict[i] += 1
else:
dict[i] = 1
推荐阅读
- angular - 是否可以在 weblogic 12c 中部署 Angular 应用程序?
- python - 如何在多个 GPU 之间拆分一个 Keras 模型
- php - php7.2.7中缺少mcrypt模块打开功能
- reactjs - 如何修复“400 Bad Request”rest-auth/registration/?
- python - 如何在已经具有复杂数据类型的数组的对角线上生成复数?
- rest - Acumatica - 我们如何通过“0”价格的 Acumatica 订单项
- winforms - 如何再次看到失控?
- html - 在 django 模板中使用变量作为 dict 键
- java - 将现有项目传递给 androidx 让我无法解析 com.google.android:support-v4:r11
- swift - 我越来越 ”
:0: 错误:无法在 cygwin 上加载 swift 标准库