【问题标题】:Putting values of same dictionary keys in one group in python在python中将相同字典键的值放在一组中
【发布时间】:2023-03-26 19:29:01
【问题描述】:

我有两个列表:

list1=[0,0,0,1,1,2,2,3,3,4,4,5,5,5]
list2=['a','b','c','d','e','f','k','o','n','q','t','z','w','l']

dictionary=dict(zip(list1,list2))

我想为每个键输出相同键的值,例如它会像这样打印:

 0 ['a','b','c']  
 1 ['d','e']  
 2 ['f','k']  
 3 ['o','n']  
 4 ['q','t']  
 5 ['z','w','l'] 

我编写了以下代码来做到这一点,但它并没有像我想的那样工作

for k,v in dictionary.items():  

     print (k,v)

您能告诉我如何修复代码,以便获得超出预期的结果吗? 提前致谢!

【问题讨论】:

  • 什么是dictionary
  • 你能说明你在哪里创建你的字典吗?
  • 对不起,我第一次忘记了,我已经更新了我的代码@Legman

标签: python list dictionary iteration key-value


【解决方案1】:

关于您的代码:

dictionary = dict(zip(list1, list2))

创建字典:

{0: 'c', 1: 'e', 2: 'k', 3: 'n', 4: 't', 5: 'l'}

除了每组中的最后一个值之外,它都会丢失所有值。您需要处理压缩列表以构建分组数据。两种方法是使用itertools.groupby()defaultdict(list),此处显示。

使用collections.defaultdict 的列表将具有来自list1 的键和来自list2 的值的项目分组。将每个列表中的项目与zip() 配对:

from collections import defaultdict

list1=[0,0,0,1,1,2,2,3,3,4,4,5,5,5]
list2=['a','b','c','d','e','f','k','o','n','q','t','z','w','l']

d = defaultdict(list)

for k,v in zip(list1, list2):
    d[k].append(v)

for k in sorted(d):
    print('{} {!r}'.format(k, d[k]))

输出:

0 ['a', 'b', 'c'] 1 ['d', 'e'] 2 ['f', 'k'] 3 ['o', 'n'] 4 ['q', 't'] 5 ['z', 'w', 'l']

由于字典中的项目是无序的,所以输出是按键排序的。

【讨论】:

    【解决方案2】:

    您显示的代码与您描述的完全不同。

    除此之外,您可以先将列表压缩,然后使用 collections.defaultdict 对同一键的值进行分组,从而将同一键的值组合在一起:

    from collections import defaultdict
    
    d = defaultdict(list)
    for k, v in zip(list1, list2):
        d[k].append(v)
    print(d)
    # defaultdict(<type 'list'>, {0: ['a', 'b', 'c'], 1: ['d', 'e'], 2: ['f', 'k'], 3: ['o', 'n'], 4: ['q', 't'], 5: ['z', 'w', 'l']})
    

    【讨论】:

      【解决方案3】:

      您可以使用itertool.groupby 获得简洁的单行解决方案:

      import itertools
      list1=[0,0,0,1,1,2,2,3,3,4,4,5,5,5]
      list2=['a','b','c','d','e','f','k','o','n','q','t','z','w','l']
      final_list = {a:[i[-1] for i in list(b)] for a, b in itertools.groupby(zip(list1, list2), key=lambda x: x[0])}
      for a, b in final_list.items():
          print(a, b)
      

      输出:

      0 ['a', 'b', 'c']
      1 ['d', 'e']
      2 ['f', 'k']
      3 ['o', 'n']
      4 ['q', 't']
      5 ['z', 'w', 'l']
      

      【讨论】:

        猜你喜欢
        • 2021-04-17
        • 1970-01-01
        • 2018-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        相关资源
        最近更新 更多