简体   繁体   English

这些for循环中哪个更有效/更好的循环编码方式

[英]which of these for-loops is more efficient/the better way to code the loop

Which is better between these two for-loops in python? python中这两个for循环哪个更好? I have "assumed" the compiler would be smart enough to do the json.loads just one time and, on its own, store the data in a temporary variable so that it could maintain the iterator needed to process the for-loop.我已经“假设”编译器足够聪明,可以只执行 json.loads 一次,并且自己将数据存储在一个临时变量中,以便它可以维护处理 for 循环所需的迭代器。 But then I started to wonder if I was mistaken and that the first style would be causing unwarranted extra steps.但后来我开始怀疑我是否弄错了,第一种风格会导致不必要的额外步骤。

for employee in json.loads(response.content)

OR或者

temp = json.loads(response.content)
   for employee in temp

Although both are essentially the same, there's one good reason to favor a temporary value: it lets you catch any errors in the call to json.loads before trying to iterate over the result.尽管两者本质上相同,但有一个很好的理由支持临时值:它可以让您在尝试迭代结果之前捕获对json.loads的调用中的任何错误。 This is consistent with keeping the code in a try statement as focused as possible.这与保持try语句中的代码尽可能集中是一致的。

try:
    employees = json.loads(response.content)
except JSONDecodeError:
    # Maybe log an error message
    # Maybe just reraise the exception
    employees = []

for employee in employees:
    ...

It's fairly clear from the documentation :文档中可以清楚地看出:

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

The expression list is evaluated once;表达式列表被评估一次;

So your worry is unfounded, and the first way is preferable unless you want to reuse the data again or writing it on the for line would make the line too long.所以你的担心是没有根据的,第一种方法更可取,除非你想再次重用数据或者将它写在for行上会使行太长。

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

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