我有这样的数据结构:
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非常陌生,在编码方面非常生疏。
谢谢你的帮助。
发布于 2021-01-13 02:36:29
这里你得到了一个单线器:
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发布于 2021-01-12 21:10:48
字典不能被真正分类,但是为了打印的目的,这是可以做到的。
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]))}")这会给你你想要的输出
发布于 2021-01-13 00:47:40
d
poll中计数选票,按步骤2的顺序获得poll d
的排序
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']https://stackoverflow.com/questions/65692029
复制相似问题