for循环评估其表达式列表多少次? [英] How many times does a for loop evaluate its expression list?

查看:61
本文介绍了for循环评估其表达式列表多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

list1 = [4,1,2,6]
for elem in sorted(list1):
    #some task

我想知道Python使用sorted()方法对列表进行多少次排序?是每次迭代还是一次?

I was wondering how many times does Python sort the list using the sorted() method? Is it for each iteration or just once?

换句话说,下面的代码更有效吗?

In other words is the following code more efficient?

list1 = [4,1,2,6]
list1 = sorted(list1)
for elem in list1:
    #some task 

推荐答案

在两个代码示例中,列表仅排序一次.

In both code examples, the list is sorted only once.

for循环头文件中in运算符右侧的表达式在循环开始之前仅被评估一次.您可以在文档:

The expression on the right of the in operator in a for-loop header is evaluated just once, before looping commences. You can read about this in the documentation:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

表达式列表被评估一次;它应该产生一个可迭代的 对象.

The expression list is evaluated once; it should yield an iterable object.

实际上,第二个代码示例效率更高,因为没有不必要的分配.

In fact, the second code example is less efficient because there is an unnecessary assignment.

这篇关于for循环评估其表达式列表多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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