python - 如何打印 2 个列表的所有相应元素并用文本分隔它们?
问题描述
我希望在 Python 中创建一个程序,提示用户输入多个整数值。该程序存储整数,计算每个整数的频率并按照下图显示频率。
我有以下代码,但我不知道如何执行最后一步(即打印“1 发生 2 次”,低于“2 发生 3 次”等)
selection = int(input("Input the number of elements to be stored in the list: "))
counter = 1
valuesList = []
while counter <= selection:
value = input("Element - " + str(counter) + ": ")
valuesList.append(value)
counter +=1
#count number occurrences of each value
import collections
counter=collections.Counter(valuesList)
#create a list for the values occurring and a list for the corresponding frequencies
keys = counter.keys()
values2 = counter.values()
print("The frequency of all elements in the list: ")
最后一次打印的下面应该是一系列打印命令:keys[0] + "occurs" + values2[0] + "times" 并继续为 'keys' 中的所有值。但是如果列表的长度根据原始“选择”输入而改变,我不知道如何打印列表中的所有值。
解决方案
像这样的东西是使用列表理解和列表的计数功能所需的紧凑解决方案
print('The frequency of all elements of the list :')
print('\n'.join({f'{i} occurs {valuesList.count(i)} times' for i in valuesList}))
推荐阅读
- google-apps-script - 是否有自定义函数或脚本可以返回 Google 表格中特定表格的 gid?
- flutter - 如何在没有构建器的情况下将 Dart 模型类转换为列表?
- django - UndefinedError: 'url_for' 未定义;在 Django 中使用 Jinja2
- jsf - 如何在 blockUI 处于活动状态时禁用 p:defaultCommand?
- powershell - awk 从 bash 到 PowerShell
- react-native - 如何在 React Native 调试器中更改字体粗细?
- node.js - Nodejs,如何在返回 Promise 的异步迭代之间延迟执行
- android - androidTestImplementation Google Truth 1.0 和实现 Google Guava 27.0.1 无法满足的版本约束
- javascript - 如何使用过滤器更改原始数组?
- ios - 在 Siri 中提问后启动应用程序并显示提问结果