如何添加数字,即在 python 中的句子前递增

How to add numbers i.e. increment before a sentence in python

如何在 python 中的句子前添加数字。代码如下

for output in outputs:
    line = tokenizer.decode(output, skip_special_tokens=True,clean_up_tokenization_spaces=True)
    print(line)

输出为:

I plan to visit Arsenal against Brighton match on April 9, and are you interested in meeting me at that match?
Hey, I'm planning to visit the game Arsenal vs Brighton on 9th April, are you interested with me in watching this game?

我正在尝试获得类似

的输出
1.) I plan to visit Arsenal against Brighton match on April 9, and are you interested in meeting me at that match?
2.) Hey, I'm planning to visit the game Arsenal vs Brighton on 9th April, are you interested with me in watching this game?

谁能帮我解决这个问题?

不需要使用额外的变量。 像这样使用索引:

for index,output in outputs:
    line = tokenizer.decode(output, skip_special_tokens=True,clean_up_tokenization_spaces=True)
    print(str(index+1) + '.) ' + line)

输出:

1.) I plan to visit Arsenal against Brighton match on April 9, and are you interested in meeting me at that match?
2.) Hey, I'm planning to visit the game Arsenal vs Brighton on 9th April, are you interested with me in watching this game?

您可以定义一个变量,在每个循环中增加它并将数字添加到打印的文本中。

n = 1
for output in outputs:
    line = f'{str(n).)} {tokenizer.decode(output, skip_special_tokens=True,clean_up_tokenization_spaces=True)}'
    n += 1
    print(line)

您可以使用 enumerate 自动递增计数器和 f 字符串:

outputs = ['line1', 'line2', 'line3']

for n, output in enumerate(outputs):
    line = output.capitalize() # use your function here
    print(f'{n+1}.) {line}')

输出:

1.) Line1
2.) Line2
3.) Line3
for n_output,output in enumerate(outputs,start=1):
    line = tokenizer.decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=True)
    print(n_output, line, sep='.) ')

Return 枚举对象。 iterable 必须是序列、迭代器或其他支持迭代的对象。

for i, output in enumerate(outputs, start=1):
    line = output
    print(i, '.)',line)