首页 > 解决方案 > 如何打印 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' 中的所有值。但是如果列表的长度根据原始“选择”输入而改变,我不知道如何打印列表中的所有值。

标签: python

解决方案


像这样的东西是使用列表理解和列表的计数功能所需的紧凑解决方案

print('The frequency of all elements of the list :')
print('\n'.join({f'{i} occurs {valuesList.count(i)} times' for i in valuesList}))

推荐阅读