当我在官方文档时,see this example:
urls = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future_to_url = {executor.submit(load_url, url, 60): url for url in urls}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
但是,我不明白表达的含义:
“future_to_url = {executor.submit(load_url,url,60):url for url”
是从哪个语法指出的?谢谢!
答案 0 :(得分:3)
它是dict
(字典)理解表达式,就像list
理解表达一样。运算符为{}
,而不是[]
。因为我们使用dictionary
定义{}
字面值。例如:
l = [1, 2, 3]
# key is `'name' + str(x)`, value is `x`
print({ 'name' + str(x): x for x in l })
# {'name2': 2, 'name3': 3, 'name1': 1}
上述代码中dict的键是'name' + str(x)
,值为x
。
因此,在{executor.submit(load_url, url, 60): url for url in urls}
中,生成的字典的关键字是executor.submit(load_url, url, 60)
,值为url
。
有关字典理解的更多信息,请参阅Dict Comprehensions。