說我有一本字典屬於鍵列表:用字典值替換鍵列表的有效方法?
dict = {"a":[1,2], "b":[3,4], "c":[5,6]}
keys = ["a","b","c"]
什麼是替換在字典中的值的列表中所有鍵的最有效方法是什麼?
即
keys = ["a","b","c"]
成爲
keys = [[1,2],[3,4],[5,6]]
說我有一本字典屬於鍵列表:用字典值替換鍵列表的有效方法?
dict = {"a":[1,2], "b":[3,4], "c":[5,6]}
keys = ["a","b","c"]
什麼是替換在字典中的值的列表中所有鍵的最有效方法是什麼?
即
keys = ["a","b","c"]
成爲
keys = [[1,2],[3,4],[5,6]]
map
很容易:
map(d.get, keys)
(或者,在Python 3.x中,list(map(d.get, keys))
)
使用list comprehension像這樣:
>>> # Please don't name a dictionary dict -- it overrides the built-in
>>> dct = {"a":[1,2], "b":[3,4], "c":[5,6]}
>>> keys = ["a","b","c"]
>>> id(keys)
28590032
>>> keys[:] = [dct[k] for k in keys]
>>> keys
[[1, 2], [3, 4], [5, 6]]
>>> id(keys)
28590032
>>>
[:]
如果您想要列表對象保持不變時,才需要。否則,你可以將其刪除:
>>> dct = {"a":[1,2], "b":[3,4], "c":[5,6]}
>>> keys = ["a","b","c"]
>>> id(keys)
28561280
>>> keys = [dct[k] for k in keys]
>>> keys
[[1, 2], [3, 4], [5, 6]]
>>> id(keys)
28590032
>>>
如果你想把所有的值的列表從字典中,使用
>>> d={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> d.values()
['a', 'b', 'c', 'd']
它返回所有包含值的列表。
如果你想鍵的子集,你可以使用:
>>> d={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> l=[1, 3]
>>> [d[x] for x in l]
['a', 'c']
請讓我知道,你所追求的......
你不應該命名變量'dict',因爲它掩蓋了內建。 – jwodder
你不能只用dict.values()獲取值嗎? – Tim