首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个测试案例Stdin (Python)

多个测试案例Stdin (Python)
EN

Stack Overflow用户
提问于 2013-11-25 03:43:05
回答 1查看 348关注 0票数 1

今年的facebook黑客杯的第一个问题有以下形式的输入:

代码语言:javascript
复制
 3 #number of test cases
 4 #number of rows of test case 1 
 . . . x
 . . x x
 . . x x
 . . . x
 2 #number of rows of test case 2
 . . x x
 . . x x
 3 #number of rows of test case 3 
 x x . .
 x x . .
 . . . x

通常,在执行代码强制问题或topcoder时,您不必彼此输入5个测试用例,只需为一个测试用例输入,然后由它们运行20-25个测试用例。

我费了很大的劲才想要操纵这些数据以使其可用,我想知道如何才能做到这一点。

例如,如果它只是

代码语言:javascript
复制
 5
 2 3 4 5 6

我可以使用the ()获得第一个数字,并且

代码语言:javascript
复制
import sys
data = []
for line in sys.stdin:
    y = [int(x) for x in line.split()]
    data.append(y)

来操纵剩下的。如果我为这个问题做了类似的事情(用str代替int ),我最终会得到一个数组,比如3,4,data,2,data,3,这些数据似乎很难操作。

如何从stdin读取多个测试用例?(即使是一般的答案也有帮助,因为问题本身并没有那么具体)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-25 03:51:00

我倾向于用发电机把这个包起来。例如:

代码语言:javascript
复制
import sys

def read_data(source):
    N = int(next(source))
    for case in range(N):
        num_rows = int(next(source))
        rows = [next(source).split() for i in range(num_rows)]
        yield rows

for case in read_data(sys.stdin):
    print case

产生

代码语言:javascript
复制
dsm@notebook:~/coding$ cat source.txt | python getdata.py 
[['.', '.', '.', 'x'], ['.', '.', 'x', 'x'], ['.', '.', 'x', 'x'], ['.', '.', '.', 'x']]
[['.', '.', 'x', 'x'], ['.', '.', 'x', 'x']]
[['x', 'x', '.', '.'], ['x', 'x', '.', '.'], ['.', '.', '.', 'x']]

这样,数据读取器就不关心源是stdin,还是文件,或者其他什么,您可以传递一些必要时删除注释的内容。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20184382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档