Python 學習筆記(十一)Python語句(二),學習筆記python語句

來源:互聯網
上載者:User

Python 學習筆記(十一)Python語句(二),學習筆記python語句

For 迴圈語句

基礎知識

for迴圈可以遍曆任何序列的項目,如一個列表或者一個字串。

文法:

for 迴圈規則:

  do sth

 1 >>> for i in "python" : #用i這個變數遍曆這個字串的每一個字元 2 ...     print i  #將遍曆的字元列印出來 3 ... 4 p 5 y 6 t 7 h 8 o 9 n10 >>> lst =["baidu","google","ali"] 11 >>> for i in lst: #用變數i遍曆這個列表,將每個元素列印出來12 ...     print i13 ...14 baidu15 google16 ali17 >>> t =tuple(lst) 18 >>> t19 ('baidu', 'google', 'ali')20 >>> for i in t: #用變數i遍曆元組,將每個元素列印出來21 ...     print i22 ...23 baidu24 google25 ali26 >>> d =dict([("lang","python"),("website","baidu"),("city","beijing")])27 >>> d28 {'lang': 'python', 'website': 'baidu', 'city': 'beijing'}29 >>> for k in d: #用變數k遍曆這個字典,將每個key列印出來30 ...     print k31 ...32 lang33 website34 city35 >>> for k in d: #用變數k遍曆字典d36 ...     print k,"-->",d[k]  #將key值和value值列印出來37 ...38 lang --> python39 website --> baidu40 city --> beijing41 >>> d.items() #以列表返回可遍曆的(鍵, 值) 元組42 [('lang', 'python'), ('website', 'baidu'), ('city', 'beijing')]43 >>> for k,v in d.items(): #用key  value遍曆d.items()的元組列表44 ...     print k,"-->",v   #取得key ,value45 ...46 lang --> python47 website --> baidu48 city --> beijing49 >>> for k,v in d.iteritems():  iteritems 返回的是迭代器  推薦使用這個50 ...     print k,v51 ...52 lang python53 website baidu54 city beijing55 >>> d.itervalues()  返回的是迭代器 56 <dictionary-valueiterator object at 0x0000000002C17EA8>57 >>>

判斷對象是否可迭代

1 >>> import collections  #引入標準庫2 >>> isinstance(321,collections.Iterable) #返回false,不可迭代3 False4 >>> isinstance([1,2.3],collections.Iterable) #返回true,可迭代5 True
 1 >>> l =[1,2,3,4,5,6,7,8,9] 2 >>> l[4:] 3 [5, 6, 7, 8, 9] 4 >>> for i in l[4:]: #遍曆4以後的元素 5 ...     print i 6 ... 7 5 8 6 9 710 811 912 >>> help(range) #函數可建立一個整數列表,一般用在 for 迴圈中13 Help on built-in function range in module __builtin__:14 15 range(...)16     range(stop) -> list of integers17     range(start, stop[, step]) -> list of integers  #計數從 start 開始,計數到 stop 結束,但不包括 stop,step:步長,預設為118 19     Return a list containing an arithmetic progression of integers.20     range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.21     When step is given, it specifies the increment (or decrement).22     For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!23     These are exactly the valid indices for a list of 4 elements.24 25 >>> range(9) 26 [0, 1, 2, 3, 4, 5, 6, 7, 8]27 >>> range(2,8)28 [2, 3, 4, 5, 6, 7]29 >>> range(1,9,3)30 [1, 4, 7]31 >>> l32 [1, 2, 3, 4, 5, 6, 7, 8, 9]33 >>> range(0,9,2)34 [0, 2, 4, 6, 8]35 >>> for i in range(0,9,2):36 ...    print i37 ...38 039 240 441 642 843 >>>
 1 #! /usr/bin/env python 2 #coding:utf-8 3  4 aliquot =[] #建立一個空的列表 5  6 for n in range(1,100):   #遍曆1到100 的整數 7     if n %3==0:          #如果被3整除 8         aliquot.append(n) #將n值添加到列表中 9 10 print aliquot

zip() 函數

函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。

如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。

返回一個列表,這列表是以元組為元素

 1 >>> a =[1,2,3,4,5] 2 >>> b =[9,8,7,6,5] 3 >>> c =[] 4 >>> for i in range(len(a)): 5 ...     c.append(a[i]+b[i]) 6 >>> for i in range(len(a)): 7 ...     c.append(a[i]+b[i]) 8 ... 9 >>> c10 [10, 10, 10, 10, 10]11 >>> help(zip)12 Help on built-in function zip in module __builtin__:13 14 zip(...)15     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]16 17     Return a list of tuples, where each tuple contains the i-th element18     from each of the argument sequences.  The returned list is truncated19     in length to the length of the shortest argument sequence.20 21 >>> a22 [1, 2, 3, 4, 5]23 >>> b24 [9, 8, 7, 6, 5]25 >>> zip(a,b)26 [(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]27 >>> c =[1,2,3]28 >>> zip(c,b)29 [(1, 9), (2, 8), (3, 7)]30 >>> zip(a,b,c)31 [(1, 9, 1), (2, 8, 2), (3, 7, 3)]32 >>> d=[]33 >>> for x,y in zip(a,b):34 ...     d.append(x+y)35 ...36 >>> d37 [10, 10, 10, 10, 10]38 >>> r =[(1,2),(3,4),(5,6),(7,8)]39 >>> zip(*r)40 [(1, 3, 5, 7), (2, 4, 6, 8)]41 >>>

enumerate()函數

函數用於將一個可遍曆的資料對象(如列表、元組或字串)組合為一個索引序列,同時列出資料和資料下標,一般用在 for 迴圈當中。

文法:

enumerate(sequence, [start=0])  

sequence -- 一個序列、迭代器或其他支援迭代對象

start -- 下標起始位置。

傳回值: enumerate枚舉對象

 1 >>> help(enumerate) 2 Help on class enumerate in module __builtin__: 3  4 class enumerate(object) 5  |  enumerate(iterable[, start]) -> iterator for index, value of iterable 6  | 7  |  Return an enumerate object.  iterable must be another object that supports 8  |  iteration.  The enumerate object yields pairs containing a count (from 9  |  start, which defaults to zero) and a value yielded by the iterable argument.10  |  enumerate is useful for obtaining an indexed list:11  |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...12  |13  |  Methods defined here:14  |15  |  __getattribute__(...)16  |      x.__getattribute__('name') <==> x.name17  |18  |  __iter__(...)19  |      x.__iter__() <==> iter(x)20  |21  |  next(...)22  |      x.next() -> the next value, or raise StopIteration23  |24  |  ----------------------------------------------------------------------25  |  Data and other attributes defined here:26  |27  |  __new__ = <built-in method __new__ of type object>28  |      T.__new__(S, ...) -> a new object with type S, a subtype of T29 30 >>> weeks =["sun","mon","tue","web","tue","fri","sta"]31 >>> for i,day in enumerate(weeks):32 ...     print str(i)+":"+day33 ...34 0:sun35 1:mon36 2:tue37 3:web38 4:tue39 5:fri40 6:sta41 >>> for i in range(len(weeks)):42 ...     print str(i)+":"+weeks[i]43 ...44 0:sun45 1:mon46 2:tue47 3:web48 4:tue49 5:fri50 6:sta51 >>> raw ="Do you love canglaoshi? canglaoshi is a good teacher."52 >>> raw_lst =raw.split(" ")53 >>> raw_lst54 ['Do', 'you', 'love', 'canglaoshi?', 'canglaoshi', 'is', 'a', 'good', 'teacher.']55 >>> for i,w in enumerate(raw_lst):56 ...     if w =="canglaoshi":57 ...             raw_lst[i]="luolaoshi"58 ...59 >>> raw_lst60 ['Do', 'you', 'love', 'canglaoshi?', 'luolaoshi', 'is', 'a', 'good', 'teacher.']61 >>> for i,w in enumerate(raw_lst):62 ...     if  "canglaoshi" in w:63 ...             raw_lst[i]="luolaoshi"64 ...65 >>> raw_lst66 ['Do', 'you', 'love', 'luolaoshi', 'luolaoshi', 'is', 'a', 'good', 'teacher.']67 >>> a =range(10)68 >>> a69 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]70 >>> s =[]71 >>> for i in a:72 ...     s.append(i*i)73 ...74 >>> s75 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]76 >>> b = [i*i for i in a] #列表解析77 >>> b78 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]79 >>> c = [i*i for i in a if i%3==0] #列表解析,加入限制條件80 >>> c81 [0, 9, 36, 81]82 >>>

列表解析

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.