Python:打印列表的最有效方式是什么? [英] Python: what is the most efficient way to print a list of lists?

查看:58
本文介绍了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:打印列表的最有效方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆