Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果直线与上面的直线相同,则向下填充/增加1_Python_Loops_Increment - Fatal编程技术网

Python 如果直线与上面的直线相同,则向下填充/增加1

Python 如果直线与上面的直线相同,则向下填充/增加1,python,loops,increment,Python,Loops,Increment,我很难根据一行内容和它上面的一行内容填写一系列数字。我有一个包含几行文本的文本文件,我想检查一行是否等于它上面的行。如果相等,则添加1,如果不相等,则使用1。输入文本为: DOLORES DOLORES GENERAL LUNA GENERAL LUNA GENERAL LUNA GENERAL NAKAR GENERAL NAKAR 我想要的输出是: 1 2 1 2 3 1 2 1 2 1 2 3 1 2 我试过了,但结果不同: fhand = open("input.txt&

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

DOLORES
DOLORES
GENERAL LUNA
GENERAL LUNA
GENERAL LUNA
GENERAL NAKAR
GENERAL NAKAR
我想要的输出是:

1
2
1
2
3
1
2
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')

主要问题是,您说要检查相同的行,但代码处理的是单个字符。对程序的琐碎跟踪显示了这一点。 看看这个可爱的参考资料

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

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)
输出: