为什么这本词典中有一个循环? [英] Why is there a loop in this dictionary?
问题描述
是否可以在字典旁边迭代列表?看起来很复杂.
Is it possible to iterate the list in side the dictionary? Looks like a complex syntax.
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
推荐答案
您正在查看词典理解;它从循环中构建字典.
You are looking at a dictionary comprehension; it builds a dictionary from a loop.
等效于:
future_to_url = {}
for url in URLS:
future_to_url[executor.submit(load_url, url, 60)] = url
但拼写更简洁.
可以执行相同的操作来生成列表:
The same can be done to produce a list:
[executor.submit(load_url, url, 60) for url in URLS]
或设置:
{executor.submit(load_url, url, 60) for url in URLS}
或在生成器表达式中延迟生成元素:
or produce the elements lazily in a generator expression:
(executor.submit(load_url, url, 60) for url in URLS)
See the List Comprehensions section of the Python tutorial, and onwards, where the other comprehensions are explained.
对领域的理解需要Python 2.7或更高版本;如果需要将其移植回较早的Python版本,则可以在dict()
函数内使用generator expression语法生成(key, value)
元组:
Dict comprehensions require Python 2.7 or newer; if you need to port this back to older Python versions, you'd use the generator expression syntax inside a dict()
function to produce (key, value)
tuples:
dict((executor.submit(load_url, url, 60), url) for url in URLS)
这篇关于为什么这本词典中有一个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!