我在哪里弄乱输出格式?

时间:2016-04-25 04:01:07

标签: python python-3.x formatting format string-formatting

因此,当我尝试运行代码时收到错误消息,我无法确定问题究竟是什么。它说这是一个ValueError,但我无法弄清楚究竟是哪一个。也许它已经晚了,但我不知所措。

这是我的代码:

def sort(count_dict, avg_scores_dict, std_dev_dict):
    '''sorts and prints the output'''
    menu = menu_validate("You must choose one of the valid choices of 1, 2, 3, 4 \n        Sort Options\n    1. Sort by Avg Ascending\n    2. Sort by Avg Descending\n    3. Sort by Std Deviation Ascending\n    4. Sort by Std Deviation Descending", 1, 4)
    print ("{}{0:27}{0:39}{0:51}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51))

    if menu == 1:       
        dic = OrderedDict(sorted(word_average_dict.items(), key=lambda x:x[1], reverse=False))
        for key in dic:
            print ("{}{0:27}{0:39:.4f}{0:51:.4f}".format(key, count_dict[key], avg_scores_dict[key], std_dev_dict[key]))
    elif menu == 2:
        dic = OrderedDict(sorted(word_average_dict.items(), key=lambda x:x[1], reverse=True))
        for key in dic:
            print ("{}{0:27}{0:39:.4f}{0:51:.4f}".format(key, count_dict[key], avg_scores_dict[key], std_dev_dict[key]))
    elif menu == 3:
        dic = OrderedDict(sorted(std_dev_dict.items(), key=lambda x:x[1], reverse=False))
        for key in dic:
            print ("{}{0:27}{0:39:.4f}{0:51:.4f}".format(key, count_dict[key], avg_scores_dict[key], std_dev_dict[key]))
    elif menu == 4:
        dic = OrderedDict(sorted(std_dev_dict.items(), key=lambda x:x[1], reverse=True))
        for key in dic:
            print ("{}{0:27}{0:39:.4f}{0:51:.4f}".format(key, count_dict[key], avg_scores_dict[key], std_dev_dict[key]))

    return None

这是我运行时的输出和错误:

You must choose one of the valid choices of 1, 2, 3, 4 
        Sort Options
    1. Sort by Avg Ascending
    2. Sort by Avg Descending
    3. Sort by Std Deviation Ascending
    4. Sort by Std Deviation Descending1
Traceback (most recent call last):
  File "C:\Users\Ryan\Documents\Program 7\Program 7.py", line 161, in <module>
    output = sort(cnt_dict, word_avg_dict, std_dev_dict)
  File "C:\Users\Ryan\Documents\Program 7\Program 7.py", line 99, in sort
    print ("{}{0:27}{0:39}{0:51}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51))
ValueError: cannot switch from automatic field numbering to manual field specification

我搞砸了什么?任何和所有的帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

您无法在自动字段编号之间来回切换 - 通过指定简单的{}获得的内容 - 以及手动字段规范,例如{0}。如果您希望重复多次相同的字段,因为在您的示例中为'Word',您还必须指定其他字段的内容。例如,您可能希望从第一个参数'Word'开始,它是元素0,第五个参数'='*51作为最后一个参数,即元素{{1} }:

4

您必须自己决定要将哪些参数放在格式字符串中。