以列表作为值的字典

Rea*_*amb 2 python dictionary tuples list

我有一个元组列表:

res=[(0, 0, 255, 0, 0),(1, 0, 255, 0, 0),(0, 1, 255, 0, 0),(1, 1, 255, 0, 0),
(4, 4, 0, 255, 0),(5, 4, 0, 255, 0),(4, 5, 0, 255, 0),(5, 5, 0, 255, 0)]
Run Code Online (Sandbox Code Playgroud)

这是我的想法:

keys = [l[2:] for l in res]
values = [l[:2] for l in res]
d=dict(zip(keys, values))
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

{(255, 0, 0): (1, 1), (0, 255, 0): (5, 5)}
Run Code Online (Sandbox Code Playgroud)

我的输出是错误的,我需要这个:

{(255, 0, 0): [(0, 0),(1,0),(0,1),(1,1)], 
(0, 255, 0): [(4,4),(5,4),(4,5),(5,5)]}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

moz*_*way 5

使用collections.defaultdict

from collections import defaultdict 

out = defaultdict(list)

for t in res:
    out[t[2:]].append(t[:2])

dict(out)
Run Code Online (Sandbox Code Playgroud)

或者用古典词典:

out = {}

for t in res:
    k = t[2:]
    if k not in out:
        out[k] = []
    out[k].append(t[:2])
Run Code Online (Sandbox Code Playgroud)

输出:

{(255, 0, 0): [(0, 0), (1, 0), (0, 1), (1, 1)],
 (0, 255, 0): [(4, 4), (5, 4), (4, 5), (5, 5)]}
Run Code Online (Sandbox Code Playgroud)