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

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

问题描述

我有以下代码:

list1 = [4,1,2,6]对于排序(list1)中的元素:#一些任务

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

也就是说下面的代码效率更高?

list1 = [4,1,2,6]列表 1 = 排序(列表 1)对于列表 1 中的元素:#一些任务

解决方案

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

在循环开始之前,for 循环标头中 in 运算符右侧的表达式只计算一次.您可以在文档中阅读相关内容:

<块引用>

for_stmt ::= "for" target_list "in" expression_list ":" 套件["else" ":"套件]

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

实际上,第二个代码示例效率较低,因为存在不必要的赋值.

I have the following code:

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

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.

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天全站免登陆