2016-03-05 34 views
-4

的數字今天是我的第一個Python日。Python:'如果num> 93'會給我帶來像94,95,996,93456

下面的代碼:

for num, line in enumerate(fo, 1): 
     if str(num) > '93971': 
       fp.write(str(num) + "\t" + str(line)) 
fo.close() 

奇怪的是,它給我帶來的是94或97或9582開頭的號碼等

我怎樣才能得到所需的嗎?

理想的情況是什麼,我想的是:

for num, line in enumerate(fo, 1): 
      if str(num) > '93971': 
        fp.write(str(num) + "\t" + str(line)) 
      if str(num) < '110000': 
        break 
    fo.close() 

非常感謝!

編輯:

那怎麼fo如下:

text one 
text 3 
text none 

這應該帶給我想:

1 text one 
2 text 3 
3 text none 
... 

這樣做,但我需要得到正是我需要的,只能從行93971至110000.

例如:

93971 text test 
93972 text test3 
... 
110000 text test2 
+2

您是否在尋找'num> 93971'?枚舉返回的索引已經是int – Ananth

+5

您正在比較兩個字符串。這是*字母*比較,而不是數字。這真的是你想要的嗎? – Carpetsmoker

+4

您正在比較字符串而不是數字,因此例如「9」大於「123612398659」,因爲「9」大於「1」。 – tdelaney

回答

1

這是做字符串比較。你可能想要比較數字。假設在一行中num是一個int - 這是因爲它是指數從enumerate回來了 - 你應該做的:

if num >= 93971 and num <= 110000: 
    fp.write(str(num) + "\t" + line) # assuming line is already a str, 
             # no need to convert 

而在你fp.write線,將其轉換爲strand比較做兩個比較,這兩個比較都需要是真實的(所以在你想要的數字範圍內)。取決於您是否想要開始/結束號碼,調整<=<。基於「真實」的問題被要求更正:

的比較可以降低到if 93971 <= num <= 110000:

編輯。

+0

已嘗試int(num),num,str(num),int(str(num)),沒有運氣 –

+0

@SeattleAls在編輯中發佈新代碼。 – seanmus

+1

@SeattleAls什麼不起作用?在你的問題中,你應該解釋「fo」包含或返回的內容。 – aneroid

0

只比較整數而不是將東西轉換爲字符串。這裏有一個工作示例,使用更小的數字作品

# write a test file 
with open('test.txt', 'w') as fp: 
    for i in range(1,1000): 
     fp.write('line {}\n'.format(i)) 

# now read lines 99 through 108 (random example) 
with open('test.txt') as fo, open('test2.txt', 'w') as fp: 
    for num, line in enumerate(fo, 1): 
     if num > 108: 
      break 
     elif num > 99: 
      fp.write(str(num) + '\t' + line) 

# now print what we wrote 
print(open('test2.txt').read()) 

When run you get 

$ python3 k.py 
100 line 100 
101 line 101 
102 line 102 
103 line 103 
104 line 104 
105 line 105 
106 line 106 
107 line 107 
108 line 108 
+0

試過這個,沒運氣 –

+0

那你能發佈一個runnable腳本嗎?這應該工作......但取決於還在發生什麼。做一些類似15至30行的事情,以便我們可以進行測試。 – tdelaney

+0

我認爲重要的是要注意第二次比較的變化方向。在原始代碼的<<中,循環會在第一行之後「break」。 @tdelaney:如果答案不起作用,你需要解釋更多關於發生的事情。 「不工作」是什麼意思? – Blckknght

相關問題