Python:打印列表列表最有效的方法是什么?
Python: what is the most efficient way to print a list of lists?
具体来说,我有一个这样的列表:[[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)
但在非常大的情况下,它并没有我希望的那么高效。我正在处理数以千计的子列表,每个子列表本身都有数以千计的数字。
我可能已经处理了子列表,所以数字是字符串或整数,这部分无关紧要。我只需要我的代码 运行 更快,目前,打印花费的时间最长。
首先将内部列表作为一个字符串加入,以创建一个字符串列表。
然后用iterator unpacking对内部列表进行解包,并使用\n
作为分隔符。
li = [[1,2,3], [4,5,6], [7,8,9], [10]]
#Join the inner lists as a string to make a list of strings
#Print them using newline separator
print(*[' '.join(map(str,item)) for item in li], sep='\n')
输出为
1 2 3
4 5 6
7 8 9
10
此外,正如@DYZ 在评论中提到的那样打印 thousands of sublists, and each of those are themselves thousands of numbers
没有意义,您可以使用一个间隔来保存它们,例如 [[1,3],[4,6],[7,9],[10]
可以这么说,打印的大部分开销来自 "setting up" 和 "tearing" 打印逻辑。因此,如果将所有内容组合成一个长字符串然后打印出来,应该会快得多:
print('\n'.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='\n')
# 191 µs ± 17.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# my solution
%timeit print('\n'.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)
具体来说,我有一个这样的列表:[[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)
但在非常大的情况下,它并没有我希望的那么高效。我正在处理数以千计的子列表,每个子列表本身都有数以千计的数字。
我可能已经处理了子列表,所以数字是字符串或整数,这部分无关紧要。我只需要我的代码 运行 更快,目前,打印花费的时间最长。
首先将内部列表作为一个字符串加入,以创建一个字符串列表。
然后用iterator unpacking对内部列表进行解包,并使用\n
作为分隔符。
li = [[1,2,3], [4,5,6], [7,8,9], [10]]
#Join the inner lists as a string to make a list of strings
#Print them using newline separator
print(*[' '.join(map(str,item)) for item in li], sep='\n')
输出为
1 2 3
4 5 6
7 8 9
10
此外,正如@DYZ 在评论中提到的那样打印 thousands of sublists, and each of those are themselves thousands of numbers
没有意义,您可以使用一个间隔来保存它们,例如 [[1,3],[4,6],[7,9],[10]
可以这么说,打印的大部分开销来自 "setting up" 和 "tearing" 打印逻辑。因此,如果将所有内容组合成一个长字符串然后打印出来,应该会快得多:
print('\n'.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='\n')
# 191 µs ± 17.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# my solution
%timeit print('\n'.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)