python中的多字典排序

2024-09-22 16:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据结构:

poll = {
  'LINK' : {'MoonRaccoon' : 1, 'TheDirtyTree' : 1},
  'ZRX' : {'MoonRaccoon' : 1, 'Dontcallmeskaface' : 1, 'TheDirtyTree' : 1},  
  'XRP' : {'Dontcallmeskaface' : 1},
  'XLM' : {'aeon' : 1, 'Bob' : 1} 
}

我希望它最终能像这样打印,按每个请求者的数量排序,然后按字母顺序打印股票代码,然后按字母顺序打印用户

!pollresults

ZRX : Dontcallmeskaface, MoonRaccoon, TheDirtyTree
LINK : MoonRaccoon, TheDirtyTree
XLM : aeon, Bob
XRP: Dontcallmeskaface

任何真正擅长分类的人都可以帮我做这件事。。我对python真的很陌生,而且对一般的编码非常生疏

谢谢你的帮助


Tags: 数据结构数量顺序字母linkbobpollaeon
3条回答

词典实际上无法进行排序,但为了便于打印,这是可以做到的


poll = {
  'LINK' : {'MoonRaccoon' : 1, 'TheDirtyTree' : 1},
  'ZRX' : {'MoonRaccoon' : 1, 'Dontcallmeskaface' : 1, 'TheDirtyTree' : 1},  
  'XRP' : {'Dontcallmeskaface' : 1},
  'XLM' : {'aeon' : 1, 'Bob' : 1} 
}

def print_polls(poll):
    for ticker in sorted(poll, key=lambda t: sum(poll[t].values()), reverse=True):
        print(f"{ticker}: {', '.join(sorted(poll[ticker]))}")

这将为您提供所需的输出

  1. poll中计算选票,获取d
  2. 递减排序d
  3. 按照步骤2的顺序获取轮询结果,并对名称列表进行排序
d = [[k, len(v)] for k, v in poll.items()]
d.sort(key=lambda name_vote: (-name_vote[-1],name_vote[0]))
pollresults = [name + ' : ' + ', '.join(sorted(poll[name].keys(), key=str.lower)) for name,vote in d]

结果:

>>> pollresults
['ZRX : Dontcallmeskaface, MoonRaccoon, TheDirtyTree', 'LINK : MoonRaccoon, TheDirtyTree', 'XLM : aeon, Bob', 'XRP : Dontcallmeskaface']

这里有一条单行线:

print (sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True))

输出:

[('ZRX', {'MoonRaccoon': 1, 'Dontcallmeskaface': 1, 'TheDirtyTree': 1}), ('LINK', {'MoonRaccoon': 1, 'TheDirtyTree': 1}), ('XLM', {'aeon': 1, 'Bob': 1}), ('XRP', {'Dontcallmeskaface': 1})]

要打印精美:

lst = sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True)

for elem in lst:
    print (elem[0],":"," ".join(elem[1].keys()))

因为我真的很喜欢一行,一切都在一行

print ("\n".join([" : ".join([elem[0]," ".join(list(elem[1].keys()))]) for elem in sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True)]))

输出:

ZRX : MoonRaccoon Dontcallmeskaface TheDirtyTree
LINK : MoonRaccoon TheDirtyTree
XLM : aeon Bob
XRP : Dontcallmeskaface

相关问题 更多 >