繁体   English   中英

Python读取文件并对其进行遍历

[英]Python reading a file and iterating over it

这是文件“ the_guessing_game”:

3
2
< 100 No
> 100 No
3
< 2 Yes
> 4 Yes
= 3 No
6
< 2 Yes
> 1 Yes
= 1 Yes
= 1 Yes
> 1 Yes
= 1 Yes

这是python代码:

infile = open("the_guessing_game")
testcases = next(infile)
print "no of testcase : %s" %(testcases)
for case in testcases:
    hints = next(infile)
    print "no of hints : %s" %(hints)
    for hint in hints:
        hint = next(infile)
        print "hint : %s" %(hint)

以上代码的结果是:

no of testcase : 3

no of hints : 2

hint : < 100 No

hint : > 100 No

no of hints : 3

hint : < 2 Yes

hint : > 4 Yes

为什么它不打印提示的范围为“否”。 提示”,此外,“不。 测试用例的数量是3,但是循环只运行了两次。 我究竟做错了什么?

更换

for case in testcases:

有:

for case in range(int(testcases)):

在前一行中,循环针对变量测试用例中包含的字符串中的每个字符运行一次。 int(testcases)一行中,循环运行int(testcases)次。

字符串测试用例由两个字符组成:三个和一个新行: '3\\n' 因此,在前一种情况下,循环运行两次,每个字符运行一次。

在某些语言中,例如bash或tcl,根据上下文,可以将字符串用作数字。 在python中,字符串是字符串,除非您将其转换,例如intfloat

暂无
暂无

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

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