python 基礎

學習python3的時候,記錄一下。
 
 
一、range(num)函數,返回0到num-1的列表
>>> list = range(100)
>>> print(list)
range(0, 100)
>>> print(type(list))
<class 'range'>
>>>

 

>>> for i in range(100):
...     sum = sum + i + 1
...
>>> print(sum)
5050

 


 
二、參數傳遞
在python中,有如下幾種參數傳遞方式:
  • 位置傳遞
  • 關鍵字傳遞
  • 參數默認值
  • 包裹傳遞(packing) vs 解包裹(unpacking)
 
混合傳遞時原則:
先位置,後關鍵字,包裹位置,包裹關鍵字
 
 
位置傳遞:
>>> def f(a,b,c):
...     return a+b+c
...
>>> print(f(1,2,3));
6

 

 
關鍵字傳遞:
>>> def f(a,b,c):
...     return a+b+c
...
>>> print(f(a=1,b=2,c=3));
6

 

 
 
默認參數值:
>>> def f1(a,b,c=10):
...     return a+b+c;
...
>>> print(f1(1,2))
13
>>> print(f1(5,2))
17
>>> print(f1(2,4,5))
11
>>> print(f1(b=6))
17

 

 
包裹傳遞:
一個星號表示傳入元組、兩個星號表示傳入字典
>>> def func(*name):
...     print(type(name))
...     print(name)
...
>>> func(1,2)
<class 'tuple'>
(1, 2)
>>> func(1,2,4,5,6)
<class 'tuple'>
(1, 2, 4, 5, 6)

 

 
>>> def func1(**name):
...     print(type(name))
...     print(name)
...
>>> func1(a=1,b=2,c=3)
<class 'dict'>
{'a': 1, 'b': 2, 'c': 3}
>>> func1(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func1() takes 0 positional arguments but 3 were given

 

 
解包裹傳遞:
>>> def func3(a,b,c):
...     print(a,b,c)
...
>>> a = (1,3,5)
>>> func3(*a)
1 3 5

 

>>> def func3(a,b,c):
...     print(a,b,c)
...
>>> b = {"a":"10","b":"20","c":"30"}
>>> func3(**b)
10 20 30

 

 
三、函數對象(lambda函數)
lambda函數語法: 
lambda a, b : a + b
lambda 參數 : 方法體

 

>>> func = lambda a, b : a + b
>>> def sum(f,a,b):
...     print("--- the sum function ---")
...     print(f(a,b))
...
>>>
>>> sum(func,10,20)
--- the sum function ---
30
>>>
 
 
 
四、內置函數:
type()    查看變量類型
dir()       查看變量有哪些方法
>>> b = {"a":"1234"}
>>>
>>> dir(b)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__'
, '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
 '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '
__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__seta
ttr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'co
py', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update
', 'values']

 

 
help()
len()     長度
open()    文件輸入和輸出
 
循環相關
range()    
enumerate()
zip()
 
iter()  循環對象
>>> list = [1,2,3,4];
>>> i = iter(list)
>>> i.__next__()
1
>>> i.__next__()
2
>>> i.__next__()
3
>>> i.__next__()
4
>>> i.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

 

 
map() 函數是 Python 內置的高階函數,它接收一個函數 f 和一個 list,並經過把函數 f 依次做用在 list 的每一個元素上,獲得一個新的 list 並返回。
如:處理數值,例如,對於list [1, 2, 3, 4, 5, 6, 7, 8], 若是但願把list的每一個元素都做平方,就能夠用map()函數:
>>> num_list = [1,2,3,4,5,6,7,8]
>>> func = lambda x : x*x
>>> num_map = map(func,num_list)
>>> print(list(num_map))
[1, 4, 9, 16, 25, 36, 49, 64]

 

 
 
如:處理字符串,假設用戶輸入的英文名字不規範,沒有按照首字母大寫,後續字母小寫的規則,請利用map()函數,把一個list(包含若干不規範的英文名字)變成一個包含規範英文名字的list:
輸入:['adam', 'LISA', 'barT']
輸出:['Adam', 'Lisa', 'Bart']
>>> str_list = ['adam', 'LISA', 'barT'];
>>> func = lambda x : x[0:1].upper() + x[1:].lower();
>>> str_map = map(func,str_list);
>>> print(list(str_map));
['Adam', 'Lisa', 'Bart']

 

 
 
filter() 函數是 Python 內置的另外一個有用的高階函數,filter()函數接收一個函數 f 和一個list,這個函數 f 的做用是對每一個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。
例如:刪除 None 或者空字符串:
>>> str_list = ['test', None, '', 'str', '  ', 'END']
>>> def is_not_empty(s):
...     return s and len(s.strip());  # and前的s用來排除None
...
>>> rs = filter(is_not_empty,str_list)
>>> print(list(rs))
['test', 'str', 'END']

 

 
reduce()函數也是Python內置的一個高階函數。reduce()函數接收的參數和 map()相似,一個函數 f,一個list,但行爲和 map()不一樣,reduce()傳入的函數 f 必須接收兩個參數,reduce()對list的每一個元素反覆調用函數f,並返回最終結果值。
而且 reduce()函數還能夠傳入第三個參數,用來作函數f的初始參數。
在Python 3裏,reduce()函數已經被從全局名字空間裏移除了,它如今被放置在fucntools模塊裏 用的話要 先引
入:
>>> from functools import reduce 
 
如reduce(f, [1, 3, 5, 7, 9], 100),則先將計算f(100,1)。
能夠用來作求和,雖然python自帶了sum函數。
例如:求積:[2, 4, 5, 7, 12]
>>> from functools import reduce
>>> num_list = [2, 4, 5, 7, 12]
>>> func = lambda x,y : x*y
>>> rs = reduce(func,num_list)
>>> print(rs)
3360

 

 
在100的基礎上求積 [2, 4, 5, 7, 12]
>>> from functools import reduce
>>> num_list = [2, 4, 5, 7, 12]
>>> func = lambda x,y : x*y
>>> rs = reduce(func,num_list,100)
>>> print(rs)
336000

 

 
 
數學運算函數:
• abs(-2) #取絕對值
• round(2.3) #取整
• pow(3,2) #乘方
• cmp(3.1, 3.2) #比較大小
• divmod(9,7) #返回除法結果和餘數
• max([2,4,6,8]) #求最大值
• min([1,2, -1, -2]) #求最小值
• sum([-1,1,5,7]) #求和


類型轉化函數:
• int(「10」) #字符轉爲整數
• float(4) #轉爲浮點數
• long(「17」) #轉爲長整數
• str(3.5) #轉爲字符串
• complex(2, 5) #返回複數 2 + 5i
• ord(「A」) #A對應的ascii碼
• chr(65) #ascii碼對應的字符
• unichr(65) #數值65對應的unicode字符
• bool(0) #轉換爲相應的真假值,0至關於False
btw: 「空」值至關於False: [], (), {}, 0, None, 0.0, ''


序列操做函數:
• all([True, 2, 「wow!"]) #是否全部元素至關於True
• any([0, 「」, False, [], None]) #是否有元素至關於True
• sorted([1,7,4]) #序列升序排序
• reversed([1,5,3]) #降序排序
• list((1,2,3)) #轉換爲表list
• tuple([4,5,4]) #轉換爲tuple
• dict(a=3,b=「hi」,c=[1,2,3]) #構建字典


 
其它函數:
 id() #查看對象的內存位置
 type() #查看對象類型
 len() #查看對象長度
• input(‘ input something ’) #等待用戶輸入
• globals() #返回全局變量名,函數名
• locals() #返回局部命名空間


 
 
 
五、面向對象
    • 私有屬性,全部方法。在方法名,屬性名前加「__」。例如: __private_name
__private_name = 1;
def __private_func(self,name):
    print(name);

 

    • 類名稱首字母大寫:
class ClassName():

 

 
六、模塊
  • 安裝pip:
# 先安裝setuptools
https://pypi.python.org/pypi/setuptools
# 後安裝pip
https://pypi.python.org/pypi/pip

  • 編譯安裝
# 編譯(若是下載的是源碼)
python setup.py build
# 安裝(全部python的模塊都適用)
python setup.py install

# 安裝模塊(安裝玩pip後)
pip install xxx
  • 引入模塊:
import module_name;
import module_name as mn;
from module_package import module_name;
from module_package import *;

 

  • 模塊引入路徑:
模塊搜索路徑:
1、程序所在的位置
2、標準庫的安裝路徑
3、操做系統環境變量PYTHONPATH指向的位置

可是若是咱們的模塊不在上述位置時,須要在環境變量中加入以下路徑:
export PYTHONPATH=$PYTHONPATH:{module_path}

 

七、python標準庫:
• 正則表達式 (re包)
• 時間與日期 (time, datetime包)
• 路徑與文件 (os.path包, glob包)
• 文件管理 (部分os包,shutil包)
• 存儲對象 (pickle包,cPickle包)
• 子進程 (subprocess包)
• 信號 (signal包)
• 線程同步 (threading包)
• 進程信息 (部分os包)
• 多進程初步 (multiprocessing包)
• 數學 (math包)
• 隨機數(random包)
• 循環器 (itertools)
• 數據庫 (sqlite3)
• …

 

• [官方文檔]
• Python 2:
• https://docs.python.org/2/library
• Python 3:
• https://docs.python.org/3/library/index.html
相關文章
相關標籤/搜索