【问题标题】:Check if duplicate exists and then append a unique digit to line?检查是否存在重复,然后在行中附加一个唯一的数字?
【发布时间】:2020-02-18 22:55:55
【问题描述】:

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是我想要的

【问题讨论】:

  • 你试过什么?您还在哪里寻找建议?你遇到了什么问题?到目前为止你写了什么代码?该代码的作用/输出是什么?

标签: python linux string file


【解决方案1】:

类似这样的:

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

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多