如何在python中为每个新的字符串实例创建一个计数器?

时间:2017-03-24 18:22:53

标签: python count

我想知道如何在列表中为特定字符串(#####)的新实例创建计数器。然后,我想将此计数器附加到字符串:

##### 
pears 
oranges 
##### 
apples 
grapes 
##### 
grapes 
oranges 
#####
apples 
pears
oranges
grapes

输出看起来像这样:

#####_1 
pears 
oranges 
#####_2    
apples 
grapes 
#####_3  
grapes 
oranges 
#####_4 
apples 
pears
oranges
grapes

1 个答案:

答案 0 :(得分:-2)

文件input.txt

##### 
pears 
oranges 
##### 
apples 
grapes 
##### 
grapes 
oranges 
#####
apples 
pears
oranges
grapes

文件run.py

lines = [l.strip() for l in open('input.txt', 'r').readlines()]
hash_count = 0

for line in lines:
    if line == '#####':
        hash_count += 1
        print(line)
    else:
        print(line + '_' + str(hash_count))

运行它:

$ python run.py

输出:

#####
pears_1
oranges_1
#####
apples_2
grapes_2
#####
grapes_3
oranges_3
#####
apples_4
pears_4
oranges_4
grapes_4

希望它有所帮助。