python - 以列表作为值的字典

标签 python list dictionary tuples

我有一个元组列表:

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)]

这是我的想法:

keys = [l[2:] for l in res]
values = [l[:2] for l in res]
d=dict(zip(keys, values))

这是我的输出:

{(255, 0, 0): (1, 1), (0, 255, 0): (5, 5)}

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

{(255, 0, 0): [(0, 0),(1,0),(0,1),(1,1)], 
(0, 255, 0): [(4,4),(5,4),(4,5),(5,5)]}

有什么想法吗?

最佳答案

使用 collections.defaultdict :

from collections import defaultdict 

out = defaultdict(list)

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

dict(out)

或者用经典词典:

out = {}

for t in res:
    k = t[2:]
    if k not in out:
        out[k] = []
    out[k].append(t[:2])

输出:

{(255, 0, 0): [(0, 0), (1, 0), (0, 1), (1, 1)],
 (0, 255, 0): [(4, 4), (5, 4), (4, 5), (5, 5)]}

关于python - 以列表作为值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72035621/

相关文章:

python - 更Pythonic的方式来做到这一点?

python - 列表中两个切片的最小-最大/最大值

python - 从包含列表的嵌套字典创建数据框

python '__file__' 未定义

python - 如何使 Tkinter 条目焦点验证不仅仅在第一次发生?

python - Django ORM - 关于 Router.allow_relation() 的困惑

python - 监控文件扭曲

python - 如果我的日期在字符串中,我如何在 Python 中对这个列表进行排序?

c++ - 使用 C++ 中的多个键之一访问相同的值?

c++ - map::find 具有可比较但不可转换为 key_type 的类型