【问题标题】:Fill down/increment by 1 if line is the same as line above it如果行与其上方的行相同,则向下填充/递增 1
【发布时间】:2021-05-02 21:27:18
【问题描述】:

我很难根据一行的内容和紧接其上方的行填写一系列数字。我有一个包含多行文本的文本文件,我想检查一行是否等于它上面的行。如果相等则加1,不相等则加1。输入文本为:

DOLORES
DOLORES
GENERAL LUNA
GENERAL LUNA
GENERAL LUNA
GENERAL NAKAR
GENERAL NAKAR

我想要的输出是:

1
2
1
2
3
1
2

我试过了,但结果不同:

fhand = open("input.txt")
fout = open("output.txt","w")

t = list()
ind = 0

for line in fhand:
    t.append(line)

for elem in t:
    if elem[0] or (not(elem[0]) and (elem[ind] == elem[ind-1])):
        ind += 1
    elif not(elem[0]) and (elem[ind] != elem[ind-1]):
        ind = 1
    fout.write(str(ind)+'\n')
fout.close()

我怎样才能得到我想要的结果?

【问题讨论】:

    标签: python loops increment


    【解决方案1】:

    主要问题是您要检查相同的行,但您的代码处理的是单个字符。对您的程序的简单跟踪显示了这一点。 请参阅debugging help 这个可爱的参考。

    您需要处理行,而不是字符。我已删除文件处理,因为它们对您的问题无关紧要。

    t = [
        "DOLORES",
        "DOLORES",
        "GENERAL LUNA",
        "GENERAL LUNA",
        "GENERAL LUNA",
        "GENERAL NAKAR",
        "GENERAL NAKAR",
        ]
    
    prev = None    # There is no previous line on the first iteration
    count = 1
    for line in t:
        if line == prev:
            count += 1
        else:
            count = 1
            prev = line
        print(count)
    

    输出:

    1
    2
    1
    2
    3
    1
    2
    

    【讨论】:

      【解决方案2】:

      像这样编辑你的条件:

      fout.write(str(1)+'\n')
      for elem in range(1,len(t)):
          if t[elem]==t[elem-1]:
              ind += 1
          else:
              ind = 1
          fout.write(str(ind)+'\n')
      

      【讨论】:

        猜你喜欢
        • 2022-08-16
        • 2014-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 2019-09-02
        相关资源
        最近更新 更多