python - 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 次
解决方案
您可以通过列表理解轻松做到这一点
lst = [5, 6, 7]
newList = [num for num in lst for i in range(3)]
推荐阅读
- c++ - MPI 客户端/服务器
- java - 可选 int 参数 '' 存在,但由于被声明为原始类型,因此无法转换为空值
- android - 导入 android studio 项目时出现 Gradle 问题
- php - Nginx 永久链接从 URL 中删除 .html
- javascript - 如何让 iframe innerHTML 表示页面上实际可见的内容?
- swift - 如何使用 Swift 显示从 Viewcontroller B 接收到的值到 Viewcontroller A tableview 自定义单元格文本视图?
- python - 使用 groupby 将数据帧转换为 dict
- javascript - 在 laravel 中检索角度参数
- ubuntu - 在 Ubuntu 上安装 RabbitMq 时出现 Erlang 依赖问题
- graph - 如何制作信封图