3 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
>>> keys = ['a','b','c']>>> value = [0, 0]>>> {key: list(value) for key in keys} {'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
這個(gè)答案是為了向任何被試圖實(shí)例化的結(jié)果搞砸的人解釋這種行為。dict帶著fromkeys()中具有可變默認(rèn)值的dict.
考慮:
#Python 3.4.3 (default, Nov 17 2016, 01:08:31)
# start by validating that different variables pointing to an
# empty mutable are indeed different references.
>>> l1 = []
>>> l2 = []
>>> id(l1)
140150323815176
>>> id(l2)
140150324024968
所以任何改變l1不會(huì)影響l2反之亦然。到目前為止,這對(duì)于任何可變的情況都是正確的,包括dict.
# create a new dict from an iterable of keys
>>> dict1 = dict.fromkeys(['a', 'b', 'c'], [])
>>> dict1
{'c': [], 'b': [], 'a': []}
這可以是一個(gè)方便的功能。在這里,我們?yōu)槊總€(gè)鍵分配一個(gè)默認(rèn)值,它也恰好是一個(gè)空列表。
# the dict has its own id.
>>> id(dict1)
140150327601160
# but look at the ids of the values.
>>> id(dict1['a'])
140150323816328
>>> id(dict1['b'])
140150323816328
>>> id(dict1['c'])
140150323816328
事實(shí)上,他們都在使用相同的裁判!對(duì)一個(gè)人的改變就是對(duì)所有事物的改變,因?yàn)樗麄儗?shí)際上是同一個(gè)對(duì)象!
>>> dict1['a'].append('apples')
>>> dict1
{'c': ['apples'], 'b': ['apples'], 'a': ['apples']}
>>> id(dict1['a'])
>>> 140150323816328
>>> id(dict1['b'])
140150323816328
>>> id(dict1['c'])
140150323816328
對(duì)許多人來(lái)說(shuō),這不是他們的本意!
現(xiàn)在,讓我們嘗試將列表的顯式副本用作默認(rèn)值。
>>> empty_list = []
>>> id(empty_list)
140150324169864
,現(xiàn)在創(chuàng)建一個(gè)具有empty_list.
>>> dict2 = dict.fromkeys(['a', 'b', 'c'], empty_list[:])
>>> id(dict2)
140150323831432
>>> id(dict2['a'])
140150327184328
>>> id(dict2['b'])
140150327184328
>>> id(dict2['c'])
140150327184328
>>> dict2['a'].append('apples')
>>> dict2
{'c': ['apples'], 'b': ['apples'], 'a': ['apples']}
還是沒(méi)有歡樂(lè)!我聽到有人喊,因?yàn)槲矣昧艘粋€(gè)空名單!
>>> not_empty_list = [0]
>>> dict3 = dict.fromkeys(['a', 'b', 'c'], not_empty_list[:])
>>> dict3
{'c': [0], 'b': [0], 'a': [0]}
>>> dict3['a'].append('apples')
>>> dict3
{'c': [0, 'apples'], 'b': [0, 'apples'], 'a': [0, 'apples']}
的默認(rèn)行為。fromkeys()是分配None價(jià)值。
>>> dict4 = dict.fromkeys(['a', 'b', 'c'])
>>> dict4
{'c': None, 'b': None, 'a': None}
>>> id(dict4['a'])
9901984
>>> id(dict4['b'])
9901984
>>> id(dict4['c'])
9901984
事實(shí)上,所有的值都是相同的(也是唯一的!)None..現(xiàn)在,讓我們以無(wú)數(shù)種方式中的一種來(lái)迭代dict并改變價(jià)值。
>>> for k, _ in dict4.items():
... dict4[k] = []
>>> dict4
{'c': [], 'b': [], 'a': []}
嗯??雌饋?lái)和以前一樣!
>>> id(dict4['a'])
140150318876488
>>> id(dict4['b'])
140150324122824
>>> id(dict4['c'])
140150294277576
>>> dict4['a'].append('apples')
>>> dict4
>>> {'c': [], 'b': [], 'a': ['apples']}
但它們確實(shí)不同[]在本例中,這是預(yù)期的結(jié)果。

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
l = ['a', 'b', 'c'] d = dict((k, [0, 0]) for k in l)
添加回答
舉報(bào)