如何跳过stdin的第一行读物?

Özl*_*lem 6 python stdin

 while 1:
     try:
         #read from stdin
         line = sys.stdin.readline()
     except KeyboardInterrupt:
         break
     if not line:
         break
     fields = line.split('#')
     ...
Run Code Online (Sandbox Code Playgroud)

我如何跳过第一行阅读stdin

Joh*_*ooy 6

infile = sys.stdin
next(infile) # skip first line of input file
for line in infile:
     if not line:
         break
     fields = line.split('#')
     ...
Run Code Online (Sandbox Code Playgroud)

  • 这比我的示例好得多:) 出于好奇:为什么不直接执行“next(sys.stdin)”?为什么要别名呢? (2认同)

ro.*_*o.e 3

您可以使用该enumerate函数来实现以下目的:

for place, line in enumerate(sys.stdin):
    if place: # when place == 0 the if condition is not satisfied (skip first line) 
        ....
Run Code Online (Sandbox Code Playgroud)

enumerate的文档。