分享
三行代码  ›  专栏  ›  技术社区  ›  BBG_GIS

如何在python中将嵌套列表作为字典值进行迭代和排序?

  •  2
  • BBG_GIS  · 技术社区  · 1 周前

    dict =  {'x': [(['a'], ['b'], ['c'], ['d'], ['e'], ['f'])],'y': [(['a'], ['b'], ['c'], ['d'], ['e'], ['f'])]}
    

    res = {'x': [(['a',1], ['b',2], ['c',3], ['d',4], ['e',5], ['f',6])]}
    

    如何在嵌套列表中添加数字?

    2 回复  |  直到 1 周前
        1
  •  2
  •   Dharman Stavros Droutsas    1 周前
    >>> dct =  {'x': [(['a'], ['b'], ['c'], ['d'], ['e'], ['f'])]}
    >>> {k:[tuple([c for c in l]+[i+1] for i,l in enumerate(t)) for t in v ] for k,v in dct.items()}
    {'x': [(['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5], ['f', 6])]}
    
    
        2
  •  2
  •   mobiusxs    1 周前

    这是您想要的:

    _dict =  {'x': [(['a'], ['b'], ['c'], ['d'], ['e'], ['f'])],'y': [(['a'], ['b'], ['c'], ['d'], ['e'], ['f'])]}
    for item in _dict:
        for index, _list in enumerate(_dict[item][0]):
            _list.append(index + 1)
    
    print(_dict)
    # {'x': [(['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5], ['f', 6])], 'y': [(['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5], ['f', 6])]}