Python: what is the most efficient way to print a list of lists?(Python:打印列表的最有效方式是什么?)
本文介绍了Python:打印列表的最有效方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具体地说,我有一个这样的列表:[[1,2,3], [4,5,6], [7,8,9], [10]]
,我想打印出来如下:
1 2 3
4 5 6
7 8 9
10
我认为这样的操作会非常有效:
a = [[1,2,3], [4,5,6], [7,8,9], [10]]
for sublist in a:
print(*sublist)
但在非常大的情况下,它的效率并不像我希望的那样高。我在处理成千上万的子列表,每个子列表本身都有数千个数字长。
我可能已经处理了子列表,所以数字是字符串或整数,这一部分并不太重要。我只需要我的代码运行得更快,而目前,打印是花费时间最长的。
推荐答案
可以说,打印的大部分开销来自于"设置"和"拆卸"打印逻辑。因此,如果您将所有内容合并为一个长字符串,然后打印它,应该会快得多:
print('
'.join(' '.join(map(str, sub)) for sub in a))
我的时间配置结果,给定以下数据和三个解决方案:
a = [list(range(10)), list(range(10, 20)), list(range(20, 30))]
# OP's original solution
%timeit for sublist in a: print(*sublist)
# 1.74 ms ± 89.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# another answer's solution
%timeit res = [' '.join(map(str,item)) for item in a]; print(*res, sep='
')
# 191 µs ± 17.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# my solution
%timeit print('
'.join(' '.join(map(str, sub)) for sub in a))
# 78.2 µs ± 5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
这篇关于Python:打印列表的最有效方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Python:打印列表的最有效方式是什么?


基础教程推荐
猜你喜欢
- 症状类型错误:无法确定关系的真值 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01