What is the meaning of a for loop in curly braces?

廉价感情. 提交于 2020-06-13 08:21:31

问题


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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/52641936/what-is-the-meaning-of-a-for-loop-in-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!