2017-06-12 43 views
0

當我在官方文檔,see this example如何理解這個表達式: 「future_to_url = {executor.submit(load_url,網址,60):URL對於URL」

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))) 

不過,我不噸understant表達的含義是:

「future_to_url = {executor.submit(load_url,網址,60):URL對於URL」

是它從該語法點?謝謝!

回答

2

這是一個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} 

的字典的在上面的代碼的關鍵是'name' + str(x),該值是x
所以在{executor.submit(load_url, url, 60): url for url in urls},生成字典的關鍵是executor.submit(load_url, url, 60),值是url

關於字典理解的更多信息,請參閱Dict Comprehensions

+0

謝謝,明白吧。 – Devin

+0

不客氣! @Devin。 – zhenguoli