Python学习小记(2)---[list, iterator, and, or, zip, dict.keys],,1.List行为可以
Python学习小记(2)---[list, iterator, and, or, zip, dict.keys],,1.List行为可以
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 purerobin 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)...97531#sorted>>> basket = [‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘]>>> for f in sorted(set(basket)):... print(f)...applebananaorangezpear
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()>>> viewdict_keys([‘a‘, ‘b‘])>>> adict[‘c‘] = 3>>> viewdict_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 44>>> 0 or ‘‘ or [][]
Python学习小记(2)---[list, iterator, and, or, zip, dict.keys]
相关内容
- Python核心编程(第二版) 第五章习题答案,python第五章
- Python:查看矩阵大小,查看列表大小,python矩阵,对于
- cygwin使用Windows下的python,,在cygwin下使用
- 如何查找python安装包的路径site-packages?,,使用命令:
- 小飞侠带你精通Python网络编程系列04-Python内置的数据类
- centos 系统上如何把python升级为3,centospython,SCL 源目前由
- python学习——读取染色体长度(七:读取fasta文件),
- 【Python3爬虫】Scrapy使用IP代理池和随机User-Agent,,在使
- Python pandas DataFrame操作,,1. 从字典创建Da
- #MySQL for Python(MySQLdb) Note,,#MySQL for
评论关闭