0

如何在单独的行上打印列表的每个单独元素,并在元素之前打印元素的行号?列表信息也将从文本文件中检索。

到目前为止,我有,

import sys
with open(sys.argv[1], 'rt') as num:
    t = num.readlines()
    print("\n"[:-1].join(t))

目前给出的读数:

Blah, blah, blah
etc, etc, etc
x, x, x

但我想要这个读数:

1. Blah, blah, blah
2. etc, etc, etc
3. x, x, x

谢谢你的帮助。

4

3 回答 3

2

您可以使用enumerate()和使用str.rstrip()从字符串中删除所有类型的尾随空格。rstrip('\n')如果您确定换行符将是\n唯一的,您也可以使用。:

for i,x in enumerate(t,1):
    print ("{0}. {1}".format(i,x.rstrip()))
于 2012-11-15T18:36:17.563 回答
0

这似乎最简单enumerate,随时打印每一行:

import sys
with open(sys.argv[1], 'r') as num:
    for i,line in enumerate(num,1):
        print("%d. %s"%(i,line[:-1]))  #equivalent to `"{0}. {1}".format(i,line[:-1])`

当然,如果你想使用,你可以将整个东西包装在一个生成器中join

def number_lines(fname):
    with open(fname,'r') as f:
       for i,line in enumerate(f,1):
           yield "%d. %s"%(i,line[:-1])

print('\n'.join(number_lines(sys.argv[1])))
于 2012-11-15T18:36:02.617 回答
0

Using fileinput.input it is possible to iterate over file line by line. When fileinput.input returns next line, we enumerate it to track line number. As input already contains newline we use end="" in print method so it doesn't append unnecessary newline. Using format to convert line number and content to formated representation.

import fileinput

for number, line in enumerate(fileinput.input(['some_file.txt']), 1):
    print('{0}. {1}'.format(number, line), end="")
于 2012-11-15T18:51:48.043 回答