代码之家  ›  专栏  ›  技术社区  ›  AlexW

ITertools按多个键分组

  •  3
  • AlexW  · 技术社区  · 7 年前

    我正在使用 itertools group by dictionary key 使用以下内容:

    host_data = []
    for k,v in itertools.groupby(temp_data, key=lambda x:x['device_id'])
        d = {}
        for dct in v:
            d.update(dct)
        host_data.append(d) 
    

    但是,如果可能,我想按“device_id”和“port_id”分组,如何向分组中添加其他键?

    2 回复  |  直到 7 年前
        1
  •  6
  •   Netwave    7 年前

    只需使用元组作为键:

    itertools.groupby(temp_data, key=lambda x:(x['device_id'], x['port_id']))
    
        2
  •  2
  •   Amadan    7 年前

    使键成为元组: key=lambda x: (x['device_id'], x['port_id']) .

    推荐文章