【问题标题】:Python: counter in a function with multiple argsPython:具有多个参数的函数中的计数器
【发布时间】:2015-10-01 21:49:26
【问题描述】:

处理一个函数,用于输入任意数量的文本文件作为 args。功能是统计每个文件的行数、字数和字符数,以及总数:

lines = words = chars = 0

def cfunc(folder, *arg):
    global lines, words, chars

    for x in arg:
        with open("{}{}".format(folder, x), "r") as inp:
            for line in inp:
                lines += 1
                words += len(line.split(" "))
                chars += len(line)
        print(x, lines, words, chars)

cfunc("C:/", "text1.txt", "text2.txt", "text3.txt")

第一个文件的计数器是正确的。对于第三个,计数器基本上显示了所有 3 个文件中的行/单词/字符的总数。据我了解,这是因为 inp 将所有 3 个文件一起读取,并且所有文件的计数器都相同。如何分开计数器以分别打印每个文件的统计信息?

【问题讨论】:

  • 你为什么使用global?!这与您想要的行为明确完全相反。如果您将lines = words = chars = 0 放入循环中,您将分别获得每个文件的计数。
  • 你为什么在这里使用全局?

标签: python


【解决方案1】:

首先,您需要重置每个文件的统计信息:

for x in arg:
    lines = words = chars = 0
    with open("{}{}".format(folder, x), "r") as inp:
        ...

其次,要保持总计数,您需要使用单独的变量,因为您现在要为每次迭代重置变量:

total_lines = total_words = total_characters = 0

def cfunc(folder, *arg):
    global total_lines, total_words, total_chars

    for x in arg:
        ...
        print(x, lines, words, chars)
        total_lines += lines
        total_words += words
        total_chars += chars

当然,如果需要,您可以将全局变量命名为 lineswordschars,然后您只需为循环中使用的变量使用不同的名称。

【讨论】:

  • A,我觉得我很接近了,该死的! :)) 单个计数器只需要在循环内,全局计数器在外。很好的答案!谢谢?
猜你喜欢
  • 2021-09-10
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多