2016-01-11 55 views
-6

我試圖在Python中找到關於+ =的信息,但找不到任何滿足我的東西。在例如20的研究演習中,他要求你用+ =重寫腳本。即使只是它的一個小例子,它可以取代什麼也是有幫助的。我怎麼可以重寫這個?例子20:努力學習Python

from sys import argv 

script, input_file = argv 

def print_all(f): 
    print f.read() 

def rewind(f): 
    print f.seek(0) 

def print_a_line(line, f): 
    print line, f.readline() 

print "Here is the file: %r" % input_file 

current_file = open(input_file) 

print_all(current_file) 

print "Now let's start from the beginning..." 

rewind(current_file) 

print "Here are the first three lines of the file:" 

current_line = 1 
print_a_line(current_line, current_file) 
current_line = current_line + 1 
print_a_line(current_line, current_file) 
current_line = current_line + 1 
print_a_line(current_line, current_file) 

current_file.close() 
+1

'n + = 1'相當於'n = n + 1' – wvdz

回答

2

+=運算符意味着添加一些東西到現有的變量。 n += 2相同n = n + 2

在你的榜樣,而不是current_line = current_line + 1,做current_line += 1

+2

有一個錯字,我的錯 – BlueMoon93

0

它的字面解釋了+=意味着這個頁面上。

http://learnpythonthehardway.org/book/ex20.html

問:什麼是+=

答:你知道英語怎麼樣,我可以改寫它是「它」嗎?或者我可以將「你是」改寫爲「你」?在英語中,這被稱爲收縮,這有點像兩個操作=+的收縮。這意味着x = x + yx += y相同。

0

+ =是Syntactic Sugar。你可以將Syntactic Sugar看作是一個額外的小東西,它可以讓事情變得更簡單或者更清晰。

這個特殊的語法糖用於向現有變量(左側的變量,也稱爲左值)添加一個值(右側的值,也稱爲右值)。

你可以寫

variable += 1 

variable = variable + 1 

,並解釋它沒有什麼不同。您也可以對其他操作員進行相同操作。

var -= 8 # Subtracting 
var *= 3 # Multiplication 
var %= 2 # Modulus (Remainder of division) 
var /= 4 # Division 

或者你根本就沒有。無論您怎麼看,都會讓您的代碼變得清晰,易於理解,並且更易於輸入。這真的是一種偏好。我通常會嘗試堅持使用多種編程風格,而這種風格往往會混淆。

+0

沒有什麼不同嗎?將'timeit('a = a + [0]','a = []')'與'+ ='版本進行比較。 –

+0

@StefanPochmann - 可能意味着「原始變量沒有差異」 –

+0

優化被高估。程序員的時間幾乎總是更有價值。除非給出一個很好的理由,否則你應該很少考慮讓你的代碼更快。大多數編譯器/解釋器可以爲你做得更好,然後你可以做得更好。我希望看到.pyc示例已經進行了優化。 –