簡體   English   中英

將值修改為 Python 字典中的特定鍵

[英]Modifying Values to Specific Keys in Python dictionary

我在下面創建了一個字典d ,並正在尋找一個帶有('a'、'b'、'c') 的字典以具有值 'd' 和 'e'。

test = ['a','b','c','d','a','b','c','e','p','q','r','s']
test2= tuple(test)
d = {test2[i:i+3]:test2[i+3] for i in range(0,len(test2)-3,1)}
print(d)

output 是:

{('a', 'b', 'c'): 'e', ('b', 'c', 'd'): 'a', ('c', 'd', 'a'): 'b', ('d', 'a', 'b'): 'c', ('b', 'c', 'e'): 'p', ('c', 'e', 'p'): 'q', ('e', 'p', 'q'): 'r', ('p', 'q', 'r'): 's'}

預期的 output 是:

{('a', 'b', 'c'): ('d','e'), ('b', 'c', 'd'): 'a', ('c', 'd', 'a'): 'b', ('d', 'a', 'b'): 'c', ('b', 'c', 'e'): 'p', ('c', 'e', 'p'): 'q', ('e', 'p', 'q'): 'r', ('p', 'q', 'r'): 's'}

問題:查看第一條評論,密鑰取其最近的值e ,所以現在我正在嘗試更改代碼以實現所需的 output? 謝謝。

選項1:

這使用 defaultdict (d = defaultdict(list)) 創建 d。

它在 for 循環中遍歷數據。 多個值附加到列表中

from collections import defaultdict

d = defaultdict(list)  # create list by default
for i in range(0,len(test2)-3):
  d[test2[i:i+3]].append(test2[i+3]) # append value into dictionary entry
                                     # which is a list 
                                     # since we used d = defaultdict(list)

選項 2:形式與選項 1 類似,但使用帶有 setdefault 的普通字典將鍵條目設為列表

d = {}
for i in range(0,len(test2)-3):
  d.setdefault(test2[i:i+3], []).append(test2[i+3])

兩個選項具有相同的 Output

defaultdict(<class 'list'>,
            {   ('a', 'b', 'c'): ['d', 'e'],
                ('b', 'c', 'd'): ['a'],
                ('b', 'c', 'e'): ['p'],
                ('c', 'd', 'a'): ['b'],
                ('c', 'e', 'p'): ['q'],
                ('d', 'a', 'b'): ['c'],
                ('e', 'p', 'q'): ['r'],
                ('p', 'q', 'r'): ['s']})

這是您也可以嘗試的另一種解決方案:

from collections import defaultdict

test = ['a','b','c','d','a','b','c','e','p','q','r','s']

d = defaultdict(list)
while len(test) >= 4:
    *key, value = test[:4] # key -> a, b, c  value -> d
    d[tuple(key)].append(value)
    test = test[1:]

print(d)
# defaultdict(<class 'list'>, {('a', 'b', 'c'): ['d', 'e'], ('b', 'c', 'd'): ['a'], ('c', 'd', 'a'): ['b'], ('d', 'a', 'b'): ['c'], ('b', 'c', 'e'): ['p'], ('c', 'e', 'p'): ['q'], ('e', 'p', 'q'): ['r'], ('p', 'q', 'r'): ['s']})

基本思想是它不斷縮小列表test直到剩下少於 4 個項目,並將前三個項目(a, b, c)分組為一個元組,然后將最后一個字符d作為一個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM