1.import问题
λ tree /F 卷 Programs 的文件夹 PATH 列表 卷序列号为 BC56-3256 D:. │ fibo.py │ ├─fibo │ │ __init__.py │ │ │ └─__pycache__ │ __init__.cpython-36.pyc │ └─__pycache__ fibo.cpython-36.pyc
在这种目录结构下
import fibo
会实际导入fibo文件夹这个module
>>> import fibo >>> fibo <module 'fibo' from 'D:\\Programs\\cmder\\Python\\fibo\\__init__.py'>
2.可以用 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']
3.循环技巧
#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
4.注意 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'])