如果线条与上方线条相同,则向下填充/递增1



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

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

主要问题是要检查相同的行,但代码处理的是单个字符。对程序的琐碎跟踪显示了这一点。请参阅此可爱的参考资料以获得调试帮助。

你需要处理线条,而不是字符。我已经取消了文件处理,因为它们对你的问题无关紧要。

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

编辑这样的条件:

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

最新更新