如果行与它上面的行相同,则用 1 填充 down/increment

Fill down/increment by 1 if line is the same as line above it

我很难尝试根据一行及其正上方的行的内容填写一系列数字。我有一个包含几行文本的文本文件,我想检查一行是否等于它上面的行。如果相等则加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()

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

像这样编辑你的条件:

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')

主要问题是您您想要检查相同的行,但您的代码处理的是单个字符。对您的程序的简单跟踪显示了这一点。 请参阅 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