简体   繁体   English

在列表理解上使用.join 是否比 python 中的简单 for 循环更快?

[英]Is using .join on list comprehension faster than a simple for loop in python?

Say I have two codes:假设我有两个代码:

a = [1,2,3,4,5,6,7,8,9,10]

print("\n".join(x for x in a))
a = [1,2,3,4,5,6,7,8,9,10]
for x in a:
    print(a)

Which one is faster and more importantly why?哪个更快,更重要的是为什么?

The first one will be throwing a type error, because you need a list of STRINGS to use join.第一个将引发类型错误,因为您需要一个字符串列表才能使用连接。

But for this purpose, i'll consider the list as string:但为此,我将列表视为字符串:

eg例如

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

For time evaluating i'll be using 'time', but i'll give you an example of how to use timeit at the end对于时间评估,我将使用“时间”,但最后我会给你一个如何使用 timeit 的例子

So let's create two functions for evaluating:因此,让我们创建两个用于评估的函数:

def first_case(a):
     start = time.time()
     print("\n".join(x for x in a))
     print(time.time() - start)

def second_case(a):
     start=time.time()
     for x in a:
         print(x)
     print(time.time() - start)

>>> first_case(a) 

1
2
3
4
5
6
7
8
9
10
3.147125244140625e-05

>>> second_case(a)
second_case(a)
1
2
3
4
5
6
7
8
9
10
6.270408630371094e-05

So here we're taking more execution time in the loop one.所以在这里我们在循环一中花费了更多的执行时间。

Also, we can improve the first expression, since we don't actually need for in the join operation.此外,我们可以改进第一个表达式,因为我们在连接操作中实际上不需要 for。

#We can rewrite the expression as the following 

>>> print("\n".join(a))
1
2
3
4
5
6
7
8
9
10

Not, the join already expect a list, so you don't need to iterate on the list.不,加入已经期望一个列表,所以你不需要在列表上迭代。

Now let's run a third_case test现在让我们运行 third_case 测试

def third_case(a):
     start = time.time()
     print("\n".join(a))
     print(time.time() - start)

>>> third_case(a)
1
2
3
4
5
6
7
8
9
10
3.0040740966796875e-05

And now we have the fastest version.现在我们有了最快的版本。

You can and should also evaluate the same functions a few more time, since we can't actually take the real results only running one time.您可以也应该多次评估相同的函数,因为我们实际上不能只运行一次真正的结果。

For that, you can use timeit.timeit.为此,您可以使用 timeit.timeit。 From the documentation :文档中:

timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM