【问题标题】:Formatting output using different elements of the same tuple使用同一元组的不同元素格式化输出
【发布时间】:2017-09-15 00:33:48
【问题描述】:

我正在寻找有关如何最好地格式化元组输出的任何建议?它涉及一个大型数据集,我已经从包含 key1:value1 的两个字典中对 [key1: [value1, value2] 进行了规范化;键1:值2。目前,我的输出会产生类似以下示例的输出:{1: [771, 'MALICE MIZER'],... 但是,我正在尝试这种格式:MALICE MIZER(1) 771。如果有人有建议,我将不胜感激它。

sorted_aid2numplay= sorted(aid2numplay.items(), key=itemgetter(1), reverse=True) 
#print(sorted_aid2numplay)

sorted_uid2numplay= sorted(uid2numplay.items(), key=itemgetter(1), reverse=True) 
#print(sorted_uid2numplay)

sorted_aid2name = sorted(aid2name.items(), key=itemgetter(0), reverse=False) 
#print(sorted_aid2name)

result = {}
for key in (aid2numplay.keys() | aid2name.keys()):
    #if key in aid2numplay: result.setdefault(key, []).append(aid2numplay[key])
    #if key in aid2name: result.setdefault(key, []).append(aid2name[key])
    if key in aid2numplay and aid2name:
        print((sorted_aid2name.itemgetter(0), key, sorted_uid2numplay.itemgetter(1))
        #print(result)

【问题讨论】:

    标签: python python-3.x sorting formatting tuples


    【解决方案1】:

    您可以使用for 循环和format 方法从您的字典中打印结果。看下面的例子

    mydict = {1: [771, 'MALICE MIZER'], 43: [536, 'HARRY POTTER']}
    for key,value in mydict.items():
        print '{v[1]}({k}) {v[0]}'.format(k=key,v=value)
    

    结果

    MALICE MIZER(1) 771
    HARRY POTTER(43) 536
    

    【讨论】:

    • 谢谢!工作完美。
    猜你喜欢
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2016-10-16
    • 1970-01-01
    相关资源
    最近更新 更多