我正在嘗試執行一個簡單的任務。我有一本帶鑰匙的字典(ti, wi)
y={('t1', 'w1'): 1, ('t2', 'w1'): 2, ('t3', 'w1'): 3, ('t1', 'w2'): 4, ('t2', 'w2'): 5, ('t3', 'w2'): 6}
我想創建一個新字典,其中的鍵是wi,而值是所有ti. 所以我想要一個輸出字典,如:
{'w1': [1, 2, 3], 'w2': [4, 5, 6]}
我寫了以下代碼:
y={('t1', 'w1'): 1, ('t2', 'w1'): 2, ('t3', 'w1'): 3, ('t1', 'w2'): 4, ('t2', 'w2'): 5, ('t3', 'w2'): 6}
y_w={}
y_t=[]
for w in range(1,3):
y_t.clear()
for t in range(1,4):
print('t= ', t, 'w= ', w, 'y=' , y['t{0}'.format(t), 'w{0}'.format(w)])
y_t.append(y['t{0}'.format(t), 'w{0}'.format(w)])
print(y_t)
y_w['w{0}'.format(w)]=y_t
print(y_w)
但我得到的結果是
{'w1': [4, 5, 6], 'w2': [4, 5, 6]}
我不明白第一個串列在哪里消失了?有人可以幫我解釋一下我錯在哪里嗎?有沒有更好的方法來做到這一點,也許沒有 for lops?
uj5u.com熱心網友回復:
您的問題在于假設在字典中設定值會以某種方式凍結串列。
串列具有相同的值并非偶然:它們是相同的,兩個指標指向同一個串列。觀察:
>>> a_dict = {}
>>> a_list = []
>>> a_list.append(23)
>>> a_dict["a"] = a_list
>>> a_list.clear()
>>> a_list.append(42)
>>> a_dict["b"] = a_list
>>> a_dict
{'a': [42], 'b': [42]}
您可以通過替換with來修復您的解決方案,這會創建一個新串列:y_t.clear()y_t = []
y = {('t1', 'w1'): 1, ('t2', 'w1'): 2, ('t3', 'w1'): 3, ('t1', 'w2'): 4, ('t2', 'w2'): 5, ('t3', 'w2'): 6}
y_w = {}
for w in range(1,3):
y_t = []
for t in range(1,4):
print('t= ', t, 'w= ', w, 'y=' , y['t{0}'.format(t), 'w{0}'.format(w)])
y_t.append(y['t{0}'.format(t), 'w{0}'.format(w)])
print(y_t)
y_w['w{0}'.format(w)]=y_t
print(y_w)
但是,正如您所懷疑的,有更簡單的方法可以做到這一點,例如Riccardo Bucco 展示的defaultdict解決方案。
uj5u.com熱心網友回復:
嘗試這個:
from collections import defaultdict
d = defaultdict(list)
for k, v in y.items():
d[k[1]].append(v)
d = dict(d)
uj5u.com熱心網友回復:
行號 10 導致了問題,如果您將其替換為它,y_t = []它將按您的預期作業
uj5u.com熱心網友回復:
您可以首先找到所有唯一鍵:
unique_keys = set(list(zip(*k))[1])
然后使用以下串列值創建字典:
{u: [v for k, v in y.items() if k[1] == u] for u in unique_keys}
uj5u.com熱心網友回復:
根據您的輸出,您可以嘗試以下操作:
y = {('t1', 'w1'): 1, ('t2', 'w1'): 2, ('t3', 'w1'): 3, ('t1', 'w2'): 4, ('t2', 'w2'): 5, ('t3', 'w2'): 6}
def new_dict_with_keys(dictionary):
new_dictionary = dict()
# Go through the dictionary keys to read each key's value
for tuple_key in dictionary:
if "w1" in tuple_key or "w2" in tuple_key:
# Determine which key to use
if "w1" in tuple_key:
key = "w1"
else:
key = "w2"
# Check if the new dictionary has the "w1" or "w2" as a an item
# If it does not, create a new list
if new_dictionary.get(key) is None:
new_dictionary[key] = list()
# Append the value in the respective key
new_dictionary[key].append(dictionary[tuple_key])
# Return the dictionary with the items
return new_dictionary
print(new_dict_with_keys(y))
# Prints: {'w1': [1, 2, 3], 'w2': [4, 5, 6]}
uj5u.com熱心網友回復:
這是使用的解決方案itertools.groupby:
import itertools as it
from operator import itemgetter
items = sorted((k, v) for (_, k), v in y.items())
groups = it.groupby(items, key=itemgetter(0))
result = {k: [v for _, v in vs] for k, vs in groups}
# {'w1': [1, 2, 3], 'w2': [4, 5, 6]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364705.html
上一篇:如何洗掉不知道列名稱的列?
