Python 学习笔记(十一)Python语句(二)

2018-06-18 01:54:14来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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 n
10 >>> lst =["baidu","google","ali"] 
11 >>> for i in lst: #用变量i遍历这个列表,将每个元素打印出来
12 ...     print i
13 ...
14 baidu
15 google
16 ali
17 >>> t =tuple(lst) 
18 >>> t
19 ('baidu', 'google', 'ali')
20 >>> for i in t: #用变量i遍历元组,将每个元素打印出来
21 ...     print i
22 ...
23 baidu
24 google
25 ali
26 >>> d =dict([("lang","python"),("website","baidu"),("city","beijing")])
27 >>> d
28 {'lang': 'python', 'website': 'baidu', 'city': 'beijing'}
29 >>> for k in d: #用变量k遍历这个字典,将每个key打印出来
30 ...     print k
31 ...
32 lang
33 website
34 city
35 >>> for k in d: #用变量k遍历字典d
36 ...     print k,"-->",d[k]  #将key值和value值打印出来
37 ...
38 lang --> python
39 website --> baidu
40 city --> beijing
41 >>> 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 ,value
45 ...
46 lang --> python
47 website --> baidu
48 city --> beijing
49 >>> for k,v in d.iteritems():  iteritems 返回的是迭代器  推荐使用这个
50 ...     print k,v
51 ...
52 lang python
53 website baidu
54 city beijing
55 >>> d.itervalues()  返回的是迭代器 
56 <dictionary-valueiterator object at 0x0000000002C17EA8>
57 >>>

判断对象是否可迭代

1 >>> import collections  #引入标准库
2 >>> isinstance(321,collections.Iterable) #返回false,不可迭代
3 False
4 >>> 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 7
10 8
11 9
12 >>> help(range) #函数可创建一个整数列表,一般用在 for 循环中
13 Help on built-in function range in module __builtin__:
14 
15 range(...)
16     range(stop) -> list of integers
17     range(start, stop[, step]) -> list of integers  #计数从 start 开始,计数到 stop 结束,但不包括 stop,step:步长,默认为1
18 
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 >>> l
32 [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 i
37 ...
38 0
39 2
40 4
41 6
42 8
43 >>>
 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 >>> c
10 [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 element
18     from each of the argument sequences.  The returned list is truncated
19     in length to the length of the shortest argument sequence.
20 
21 >>> a
22 [1, 2, 3, 4, 5]
23 >>> b
24 [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 >>> d
37 [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.name
17  |
18  |  __iter__(...)
19  |      x.__iter__() <==> iter(x)
20  |
21  |  next(...)
22  |      x.next() -> the next value, or raise StopIteration
23  |
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 T
29 
30 >>> weeks =["sun","mon","tue","web","tue","fri","sta"]
31 >>> for i,day in enumerate(weeks):
32 ...     print str(i)+":"+day
33 ...
34 0:sun
35 1:mon
36 2:tue
37 3:web
38 4:tue
39 5:fri
40 6:sta
41 >>> for i in range(len(weeks)):
42 ...     print str(i)+":"+weeks[i]
43 ...
44 0:sun
45 1:mon
46 2:tue
47 3:web
48 4:tue
49 5:fri
50 6:sta
51 >>> raw ="Do you love canglaoshi? canglaoshi is a good teacher."
52 >>> raw_lst =raw.split(" ")
53 >>> raw_lst
54 ['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_lst
60 ['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_lst
66 ['Do', 'you', 'love', 'luolaoshi', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
67 >>> a =range(10)
68 >>> a
69 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
70 >>> s =[]
71 >>> for i in a:
72 ...     s.append(i*i)
73 ...
74 >>> s
75 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
76 >>> b = [i*i for i in a] #列表解析
77 >>> b
78 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
79 >>> c = [i*i for i in a if i%3==0] #列表解析,加入限制条件
80 >>> c
81 [0, 9, 36, 81]
82 >>>

列表解析

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:第一周Python讲课内容--日记

下一篇:字典的案例演示