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

标签 python linux string file

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/

相关文章:

python - Django/South 在 python manage.py schemamigration testapp --initial 上设置失败

python - 如何在事件回调之间保持 python 生成器的状态

python - 结构重新启动我的 supervisord 服务终止服务

python - 如何在 Pandas 数据框中组合 AND 和 OR 运算符?

python - 为什么 `poll.poll` 比 `epoll.poll` 快?

arrays - 编译时错误

Javascript Regex 只替换第一次匹配出现

linux - 在哪里可以找到架构/设置源?

linux - 即使未达到 limit_maxbytes,Memcached 也会开始逐出项目

c++ - 如何按特定模式对字符串数组进行排序