问题
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