【问题标题】:Is there any way to make this code better?有没有办法让这段代码更好?
【发布时间】:2015-01-10 11:03:54
【问题描述】:

我有包含这种格式的足球结果的 TXT 文件:

1-0
2-0
2-3
etc...

我想计算每个结果以了解该文件中有多少。我有代码来计算它:

def find_result(self):
    file = open("results.txt", "r")
    result_00 = 0
    result_01 = 0
    result_02 = 0
    result_03 = 0
    result_10 = 0
    result_11 = 0
    result_12 = 0
    result_13 = 0
    result_20 = 0
    result_21 = 0
    result_22 = 0
    result_23 = 0
    result_30 = 0
    result_31 = 0
    result_32 = 0
    result_33 = 0
    result_other = 0
    results = 0
    for line in file:
        results += 1
        line = line.rstrip()
        if line == '0-0':
            result_00 += 1
        elif line == '0-1':
            result_01 += 1
        elif line == '0-2':
            result_02 += 1
        elif line == '0-3':
            result_03 += 1
        elif line == '1-0':
            result_10 += 1
        elif line == '1-1':
            result_11 += 1
        elif line == '1-2':
            result_12 += 1
        elif line == '1-3':
            result_13 += 1
        elif line == '2-0':
            result_20 += 1
        elif line == '2-1':
            result_21 += 1
        elif line == '2-2':
            result_22 += 1
        elif line == '2-3':
            result_23 += 1
        elif line == '3-0':
            result_30 += 1
        elif line == '3-1':
            result_31 += 1
        elif line == '3-2':
            result_32 += 1
        elif line == '3-3':
            result_33 += 1
        else:
            result_other += 1
    print('[0-0]' + str(result_00))
    print('[0-1]' + str(result_01))
    print('[0-2]' + str(result_02))
    print('[0-3]' + str(result_03))
    print('[1-0]' + str(result_10))
    print('[1-1]' + str(result_11))
    print('[1-2]' + str(result_12))
    print('[1-3]' + str(result_13))
    print('[2-0]' + str(result_20))
    print('[2-1]' + str(result_21))
    print('[2-2]' + str(result_22))
    print('[2-3]' + str(result_23))
    print('[3-0]' + str(result_30))
    print('[3-1]' + str(result_31))
    print('[3-2]' + str(result_32))
    print('[3-3]' + str(result_33))
    print('[OTHER]' + str(result_other))
    print('Matches: ' + str(results))

我认为这样做不是好方法(我的意思是代码太多),有没有更好的解决方案来做到这一点?谢谢你

【问题讨论】:

  • @Jongware:这不是一个有效的离题原因。这个问题对于 Stack Overflow 来说太宽泛了(我们可以通过不同的方式改进它),我们或许可以指出 Code Review 是一个更好的提问地方。

标签: python python-3.x


【解决方案1】:
# import Counter for Counting the number of occurances of each items
from itertools import Counter

# Open the file for reading
with open("results.txt", "r") as input_file:

    # Create the counter object with the lines read from the file
    c = Counter(line.rstrip() for line in input_file)

    # Print the actual item (key) and the number of occurances (count)
    for key, count in c.items():
        print("[{}] - {}".format(key, count))

    # Find the total number of elements encountered, by adding all the counts
    print(sum(c.values())

【讨论】:

    【解决方案2】:

    作为一种更 Pythonic 的方式,您可以使用 collections.Counter 来达到这个目的:

    from collections import Counter
    c_dic=Counter(open("results.txt", "r").readlines())
    

    而且您有很多选择来打印您的字典或项目,因为您没有嵌套字典,因此无需遍历项目并打印它们您可以使用json.dumps 打印带有任意缩进的字典:

    from collections import Counter
    import json
    print json.dumps(Counter(open("newefile.txt", "r").readlines()),indent=4)
    

    【讨论】:

    • @Mateusz 欢迎您! ;)
    • 我还有一个问题。如果我想计数然后分配给变量怎么办?我需要它来与他们一起做其他事情——这就是我使用 result_00 等变量的原因。
    • 因为你有一本字典,你可以通过像c_dic[0] 这样的索引来访问你的值,这是一种比初始大量变量更有效的方法!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多