gpt4 book ai didi

python - 检查是否存在重复,然后在行中附加一个唯一的数字?

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:06 25 4
gpt4 key购买 nike

INPUT.TXT 看起来像这样 -

pr-ec2_1034
pr-ec2_1023
pr-ec2_1099

我想编写一个 python 脚本,它将读取此文件并将 +1 添加到数字最高的行,然后打印该行。

所需的输出 -

pr-ec2_1100

现在我可以为所有行添加 +1,例如 -

def increment_digits(string):
return ''.join([x if not x.isdigit() else str((int(x) + 1) % 10) for x in string])

with open('INPUT.txt', 'r') as file:
data = file.read()
print(increment_digits(data))

输出-

pr-ec3_2145
pr-ec3_2134
pr-ec3_2134

但这不是我想要的。我想找到 input.txt 中结尾编号最大的行,并仅在(最后一个下划线)之后的该行添加 +1

pr-ec2_1100就是我想要的

最佳答案

类似这样的事情:

with open('input.txt') as f:
lines = [l.strip() for l in f.readlines()]
numbers = [int(l.split('_')[1]) for l in lines]
_max = max(numbers)
result = _max + 1
print('result: pr-ec2_{}'.format(result))

输出

pr-ec2_1100

关于python - 检查是否存在重复,然后在行中附加一个唯一的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com