花括号中的for循环是什么意思

花括号中的for循环是什么意思

本文介绍了花括号中的for循环是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

what-is-the-意思-curly-大括号说它们用于词典,但是这个例子呢?

what-is-the-meaning-of-curly-braces says that they are used for dictionaries, but what about this example?

resp = {
    requests.get('http://localhost:8000')
    for i in range(20)
}

来自此处(实际上,它使用[],但它也可以与{}一起使用).这是什么意思,为什么这个循环是颠倒的?

Taken from here (actually it uses [], but it works with {} as well). What is the meaning of this, and why is this loop upside-down?

推荐答案

弯括号也用于集合.这是集合理解.它创建20个requests.get对象的集合,仅保留唯一的对象.

Curly braces are also used for sets. This is a set comprehension. It creates the set of 20 requests.get objects, keeping only the unique ones.

如果使用[]而不是{},则表示列表理解.它们是相似的,但是有两个区别

If you use [] instead of {} it is a list comprehension. They are similar, but have two differences

  • 列表是已排序
  • 列表可以具有个重复元素
  • the list is ordered
  • the list can have duplicate elements

此外,正如您提到的,这是发出请求的一种不好的方式.理解应该用于创建列表/集合,而不是用于作为副产品调用许多命令.在这种情况下,一个简单的for循环会更好,使意图更清晰.

Also, as you mention, this is a bad way to make requests. Comprehensions should be used for creating a list/set, not for calling a number of commands as a by-product. In that case, a simple for-loop is better, it makes the intent clearer.

这篇关于花括号中的for循环是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:44