讀書筆記--Python基礎教程 001

來源:互聯網
上載者:User

標籤:結果   ann   字串   字元   math   空格   列印   包含   簡單   

name = raw_input(‘please enter your name: ‘) or ‘<unknown>‘

換句話說,如果raw_input語句的傳回值為真(不是Null 字元串),那麼他的值就會賦給name,否則將預設的‘<unknown>’賦值給name。

這類短路邏輯可以用來實現C和Java中所謂的‘三元運算子’(或條件運算子)。

a if b else c

如果b為真,返回a,否則,返回c。(注意,這個運算子不用引入臨時變數,就可以直接使用,從而得到與raw_input例子中同樣的結果。)

 

while 迴圈

name = ‘‘

while not name:  #改為while not name.strip(): 是不是更合理呢?!

  name = raw_input(‘please enter your name: ‘)

print ‘Hello, %s!‘ %name

這個簡單的while迴圈,讓輸入name,但是沒有考慮到name 是空格的情況,是空格了雖然不報錯,你也不知道名字啊啊啊啊,嘿嘿

for 迴圈

words = [‘this‘, ‘is‘, ‘an‘, ‘ex‘, ‘parrot‘]

for word in words:

  print word

因為迭代(迴圈的另外一種說法)某範圍的數字是常見的,所以有個內建的範圍函數供使用:

>>> range(0,10)  #話說此函數又下限(即0),但不包含上限()

[0,1,2,3,4,5,6,7,8,9]

_____________________________________________________

提示:如果能使用for迴圈,就盡量不要使用while 迴圈。

當然還有個xrange 函數,當迭代一個巨大的序列時 xrange函數 會更高效,不過一般就算了。

 

一些迭代工具:

並行迭代

names = [‘anne‘, ‘beth‘, ‘george‘, ‘damon‘]

ages = [12, 34,23,103]

如果想列印名字和對應的年齡,可以向下面這樣做:

for i in range(len(names)):

  print names[i], ‘is‘, ages[i], ‘years old‘

 

而內建的 zip 函數就可以用來進行並行迭代,可以把兩個序列‘壓縮’在一起,然後返回一個元組的列表:

>>>zip(names, ages)

[(‘anne‘, 12), (‘beth‘, 34), (‘george‘, 23), (‘damon‘, 103)]

現在我可以在迴圈中解包元組:

for name, age in zip(names, ages):

  print name , ‘is‘, age, ‘years old‘

zip 函數也可以作用於任意多的序列。 關於它很重要的一點是zip可以處理不等長的序列,當最短的序列 “用完” 的時候就會停止。

for example #(容我賣弄風騷一下,呵呵)

>>>zip(range(5), xrange(10000000))

[(0,0), (1,1), (2,2), (3,3), (4,4)]

在上面的代碼中,不推薦使用range 替換xrange ——儘管只需要前5個數字, 但是range會計算所有的數字,這要花費很長的時間。

而使用xrange就沒有這個問題了,它只計算前5個數字。

 

for index, string in enumerate(strings):

  if ‘xxx‘ in string:

    string[index] = ‘[censored]‘

enumerate這個函數可以在提供索引的地方迭代 “索引-值” 對。

 

迴圈中的else子句

from math import sqrt

for n in range(99,81, -1):

  root = sqrt(n)

  if root == int(root):

    print n

    break

else:

  print ‘Didnt find it !‘

 

列表推導式——輕量級迴圈

列表推導式(list comprehension)是利用其它列表建立新列表(類似數學術語中的集合推導式)的一種方法。

>>>[x*x for x in range(10)]

[0,1,4,9,16,25,36,49,64,81]

>>>[x*x for x in range(10) if x%3 == 0 ]

[0,9,36,81]

也可以增加更多for 語句的部分:

>>>[(x,y) for x in range(3) for y in range(3)]

[(0,0), (0,1), (0,2), (1,0), (1,1), ……]

作為對比,下面的代碼使用兩個for 語句建立了相同的列表:

result = []

for x in range(3):

  for y in range(3):

    result.append((x,y))

 

pass、del、exec

 

讀書筆記--Python基礎教程 001

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.