Python学习小记(2)---[list, iterator, and, or, zip, dict.keys]

1.List行为

可以用 alist[:] 相当于 alist.copy() ,可以创建一个 alist 的 shallo copy,但是直接对 alist[:] 操作却会直接操作 alist 对象

>>> alist = [1,2,3]
>>> blist = alist[:]               #assign alist[:] to blist
>>> alist
[1, 2, 3]
>>> blist
[1, 2, 3]
>>> blist[2:] = ['a', 'b', 'c']   #allter blist
>>> alist [1, 2, 3] >>> blist [1, 2, 'a', 'b', 'c'] >>> alist[:] = ['a', 'b', 'c'] #alter alist[:] >>> alist ['a', 'b', 'c']

2.循环技巧

#list
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

#zip函数
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue. #reversed & sorted #Note: 这两个函数不修改参数本身,返回一个iterator #reversed >>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1 #sorted >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orangez pear

3.

enumerate()函数可以把创建ist,str的可迭代对象,迭代对象每次返回一个(index, value),形式的元组

>>> astr = 'abc'                        
>>> alist = [1,2,3]                     
>>> enumerate(astr)                     
<enumerate object at 0x0374D760>        
>>> enumerate(alist)                    
<enumerate object at 0x0374D698>        
>>> def print_iterator(iterator):       
...     for ele in iterator:            
...             print(ele) ... >>> print_iterator(astr) a b c >>> print_iterator(enumerate(astr)) (0, 'a') (1, 'b') (2, 'c') >>> print_iterator(enumerate(alist)) (0, 1) (1, 2) (2, 3) >>> 

4.zip()示例

>>> a = [1,2,3]                                       
>>> b = ['a', 'b', 'c']                               
>>> c = ['one', 'two', 'three']                       
>>> a,b,c                                             
([1, 2, 3], ['a', 'b', 'c'], ['one', 'two', 'three']) 
>>>                          
>>> def print_iterator(iterator): ... for ele in iterator: ... print(ele) ... >>> >>> print_iterator(zip(a)) (1,) (2,) (3,) >>> print_iterator(zip(a,b)) (1, 'a') (2, 'b') (3, 'c') >>> >>> print_iterator(zip(a,b,c)) (1, 'a', 'one') (2, 'b', 'two') (3, 'c', 'three') 

5.

注意 adict.keys() 返回的只是 adict 的 keys 的视图

>>> adict = dict(a=1, b=2)
>>> adict
{'a': 1, 'b': 2}
>>> view = adict.keys()
>>> view
dict_keys(['a', 'b']) >>> adict['c'] = 3 >>> view dict_keys(['a', 'b', 'c'])

6.不一样的逻辑运算返回值

大概规则就是返回第一个可以判别表达式真假对象

>>> '' and 'a' and 'b'
''
>>> 'c' and '' and 'b'
''
>>> 'c' and 0 and 'b'
0
>>> '' or 'a' or 'b'
'a'
>>> 'c' or '' or 'b'
'c'
>>> '' or 0 or 'b'
'b'
>>> 1 and 3 and 4
4
>>> 0 or '' or []
[]

猜你喜欢

转载自www.cnblogs.com/liupy/p/9917003.html