1. 程式人生 > >Python學習小記(1)

Python學習小記(1)

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'])