Python learning notes (11) Python statements (2), learning notes python statements
For Loop statement
Basic knowledge
A for loop can traverse projects in any sequence, such as a list or a string.
Syntax:
For Loop rules:
Do something
1 >>> for I in "python": # Use the I variable to traverse every character of this string. 2... print I # print the traversal characters 3... 4 p 5 y 6 t 7 h 8 o 9 n10 >>> lst = ["baidu", "google", "ali"] 11 >>>> for I in lst: # use variable I to traverse this list and print each element 12... print i13... 14 baidu15 google16 ali17 >>> t = tuple (lst) 18 >>> t19 ('baidu', 'Google ', 'Ali') 20 >>> for I in t: # use variable I to traverse the tuples and print each element out 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: # Use the variable k to traverse this dictionary and print each key 30... print k31... 32 lang33 website34 city35 >>> for k in d: # Use the variable k to traverse the dictionary d36... print k, "-->", d [k] # print the key value and value 37... 38 lang --> python39 website --> baidu40 city --> beijing41 >>> d. items () # returns a list of traversal (Key, value) tuples 42 [('lang ', 'python'), ('website', 'baidu '), ('city', 'beijing')] 43 >>> for k, v in d. items (): # use key value to traverse d. list of items () tuples 44... print k, "-->", v # Get key, value45... 46 lang --> python47 website --> baidu48 city --> beijing49 >>> for k, v in d. iteritems (): iteritems returns the iterator. We recommend that you use this 50... print k, v51... 52 lang python53 website baidu54 city beijing55 >>> d. itervalues () returns the iterator 56 <dictionary-valueiterator object at 0x0000000002C17EA8> 57 >>>
Determine whether objects can be iterated
1 >>> import collections # introduce the standard library 2 >>> isinstance (321, collections. iterable) # false is returned. 3 False4 cannot be iterated.> isinstance ([1, 2.3], collections. iterable) # Return true, can iterate 5 True
1 >>> l = [1, 3, 4, 5, 6, 7, 8] 2 >>> l [4:] 3 [5, 6, 7, 8, 9] 4 >>> for I in l [4:]: # traverse elements 5 after 4... print I 6... 7 5 8 6 9 710 811 912 >>> help (range) # The function creates an integer list, usually used in a for loop 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 # Count starts from start and ends from stop, but does not include stop, step: step. The default value is 118 19 Return a list co. Ntaining an arithmetic progression of integers.20 range (I, j) returns [I, I + 1, I + 2,..., J-1]; start (!) Ults 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 () 28 [2, 3, 4, 5, 6, 7] 29 >>> range (, 3) 30 [1, 4, 7] 31 >>> l32 [1, 2, 3, 4, 5, 6, 7, 8, 9] 33 >>> range (, 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 = [] # create an empty list 5 6 for n in range (1,100 ): # traverse an integer from 1 to 100 7 if n % 3 = 0: # if 3 is divisible by 8 aliquot. append (n) # add n value to the List 9 10 print aliquot
Zip () function
The function is used to package the corresponding elements of an object into tuples and return a list composed of these tuples.
If the number of elements in each iterator is different, the returned list length is the same as that of the shortest object. Using the * operator, you can decompress the tuples into a list.
Returns a list, which uses tuples as elements.
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 () function
A function is used to combine a Data Object (such as a list, tuples, or string) that can be traversed into an index sequence and list data and data subscript at the same time. It is generally used in a for loop.
Syntax:
Enumerate (sequence, [start = 0])
Sequence-a sequence, iterator, or other supporting iteration objects
Start -- start position of the subscript.
Returned value: enumerate enumeration object
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 Rgument.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 (we Eks): 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? ', 'Hangzhoushi', '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? ', 'Luolaosshi', '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', 'luolaosshi', 'luolaosshi ', '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] # list Resolution 77> b78 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 79 >>> c = [I * I for I in a if I % 3 = 0] # list parsing, add constraints 80 >>> c81 [0, 9, 36, 81] 82 >>>
List Parsing