首页 > 解决方案 > Python如何多次但按顺序打印列表?

问题描述

我有将数字添加到由用户输入确定的范围内的列表的代码。

user_input = input("Enter a min integer: ")
minInt = int(user_input)

user_input = input("Enter a max integer: ")
maxInt = int(user_input)

num_range = range(minInt,maxInt+1)
num_list = list(num_range)
print("Here is a list of numbers constructed: " + str(num_list))

目前它的工作原理如下。如果用户输入 5 和 7,那么产生的输出是 Here is a list of numbers constructed: [5, 6, 7]

然而,我的目标是按顺序打印列表中的每个元素三次。因此,上面的输出将改为如下所示, Here is a list of numbers constructed: [5, 5, 5, 6, 6, 6, 7, 7, 7]其中每个元素总共打印了 3 次

标签: python

解决方案


您可以通过列表理解轻松做到这一点

lst = [5, 6, 7] 
newList = [num for num in lst for i in range(3)]

推荐阅读