简体   繁体   English

如何跳过(原始)输入的一行,Python 3

[英]How to skip a line of (raw) input, Python 3

I am completing the following HackerRank challenge . 我正在完成以下HackerRank挑战 I am fed the following input: 我收到以下输入:

4
2 4 5 9
4
2 4 11 12

Let's say though I just want the 2nd and 4th lines of input (and assume all input will look like this). 假设我只想要输入的第二行和第四行(并假设所有输入看起来像这样)。 At the moment I'm implementing a hackneyed solution: 目前,我正在实施一个破解方案:

seta = set()
setb = set()
delete = input()
seta = input().split()
delete = input()
setb = input().split()

I don't use delete later in the program. 我稍后在程序中不使用delete Is there a better, more exact and concise way forward? 有没有更好,更精确和简洁的方法?

Loop over the sys.stdin object ; 循环sys.stdin对象 ; it is a regular file and supports iteration. 它是一个常规文件,并支持迭代。 You can use an itertools.islice() object to skip every second line: 您可以使用itertools.islice()对象跳过第二行:

import sys
from itertools import islice

second_lines = islice(sys.stdin, None, None, 2)
seta = set(map(int, next(second_lines).split()))
setb = set(map(int, next(second_lines).split()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM