簡體   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