python 內置函數一覽

int(x, base=10) 將一個字符串或數字轉換爲整型, 默認十進制
>>> int('120')
120
>>> int(120.12)
120
>>> int('10', base=16)
16
str() 將對象轉化爲適於人閱讀的形式,即字符串
# 數字轉中文
>>> str(100)
'100'
# unicode 轉中文
>>> str('\u6d4b\u8bd5')
'測試'
dict() 初始化一個字典
>>> dict()
{}
>>> dict(a=1,b=2)
{'a': 1, 'b': 2}
list([iterable]) 初始化一個列表
>>> list()
[]
>>> list(range(5))
[0, 1, 2, 3, 4]
tuple([iterable]) 初始化一個元祖
>>> tuple()
()
>>> tuple(range(1))
(0,)
set([iterable]) 初始化一個集合(無序不重複)

關於set的操作可以參考 https://blog.csdn.net/youzi_yun/article/details/101554342

>>> set()
set()
>>> set([1,2,3,2,4])
{1, 2, 3, 4}
abs() 返回數字的絕對值
>>> abs(-1)
1
>>> abs(1)
1
divmod() 把除數和餘數運算結果結合起來,返回一個包含商和餘數的元組(a // b, a % b)
>>> divmod(7,3)
(2, 1)
>>> divmod(10,2)
(5, 0)
>>> 
input() 獲取控制檯的輸入
>>> a = input("input:")
input:test
>>> a
'test'
open(name[, mode[, buffering]]) 打開一個文件,創建一個 file 對象, 一般結合上下文管理器 with 使用
>>> with open('test.txt', 'r') as f:
...     print(f.readline())
... 
hello world!
staticmethod() 靜態方法

用作定義類裏的靜態方法,靜態方法中不需要額外定義參數,因此在靜態方法中引用類屬性的話,必須通過類對象來引用。

class A:
   @staticmethod
   def test():
        print('test-----')

調用方式:A.test()
all(iterable) 如果給定的可迭代對象 中的所有元素都爲 TRUE則返回 True,否則返回 False。
>>> all([1,2,3,4])
True
>>> all([0,1,2])
False
any(iterable) 如果給定的可迭代對象 中的所有元素至少有一個爲 True 則返回 True,所有元素都爲False則返回 False。
>>> all([1,2,3,4])
True
>>> all([0,1,2])
True
>>> all([0,'',False])
Flase
enumerate(iterable, [start=0]) 在可迭代對象中添加一個索引序列,一般用在 for 循環當中。

Python 2.3. 以上版本可用,2.6 添加 start 參數。

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three
ascii 將傳入的對象轉爲 ASCII 表達式
>>> ascii('測試')
"'\\u6d4b\\u8bd5'"
>>> str('\u6d4b\u8bd5')
'測試'
bin 返回整數的二進制表達式
>>> bin(1)
'0b1'
>>> bin(8)
'0b1000'
>>> 
callable 判斷一個對象是否是可調用的(是否實現了__call__方法)
>>> callable(1)
False
>>> callable(str)
True
chr 返回一個整數的Unicode 字符串
>>> chr(1)
'\x01'
>>> chr(10)
'\n'
>>> chr(15)
'\x0f'
compile(source, filename, mode[, flags[, dont_inherit]]) 編譯一段源碼使其可以被exec() 或 eval() 調用
參數
source -- 字符串或者AST(Abstract Syntax Trees)對象。。
filename -- 代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認的值。
mode -- 指定編譯代碼的種類。可以指定爲 exec, eval, single。
flags -- 變量作用域,局部命名空間,如果被提供,可以是任何映射對象。。
flags和dont_inherit是用來控制編譯源碼時的標誌

>>> a = compile('print(2*3)','', 'eval')
>>> eval(a)
6
>>> a = compile('print(2*3)','', 'exec')
>>> exec(a)
6
eval 執行一個字符串表達式,並返回表達式的值。
>>> eval('print(5*5)')
25
>>> eval('8+2')
10

# 還能返回表達式的原始類型
>>> ret = eval("{'a':1}")
>>> type(ret)
<class 'dict'>
>>> ret
{'a': 1}
exec 作用同eval,不同的是,exec 可以執行一個代碼塊,eval只能執行一個表達式
>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax
delattr(obj, attribute_name) 從給定對象中刪除指定屬性, 傳入參數爲 對象,屬性的字符串名稱
>>> class A:
...     a = 1
...     b = 2
... 
>>> print(A.a)
1
>>> delattr(A, 'a')
>>> print(A.a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'A' has no attribute 'a'
>>> print(A.b)
2
format 返回 value.format(format_spec)

通常用於格式化字符串

>>> '{}今年5歲了'.format('小明')
'小明今年5歲了'
getattr(object, name, default=None) 返回一個對象的屬性,getattr(x, ‘y’) 等同於 x.y,屬性不存在的時候返回default值
>>> getattr(int, '__add__')
<slot wrapper '__add__' of 'int' objects>
>>> getattr(int, '__sum__')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'int' has no attribute '__sum__'
globals 以dict的形式返回當前環境中的全局變量
>>> globals()
{'__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__package__': None}
>>> a = 'test'
>>> globals()
{'__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 'test', '__package__': None}
hasattr 判斷對象是否有某個屬性

通過 getattr 實現,若捕獲AttributeError則返回False,否則返回True

>>> hasattr(int,'__add__')
True
>>> hasattr(int,'__sum__')
False
hash 返回一個對象的哈希值,若判斷兩個對象相等,那他們的哈希值必然相等,但是倒序這個對象,哈希值不一定相等
>>> hash('abc')
4697863510219724172
>>> a = 'abc'
>>> hash(a)
4697863510219724172
help 通過help 會展示出對象的所有屬性, 是對 pydoc.help 的封裝
>>> help(int)
hex 返回一個整數的16進製表達式
>>> hex(16)
'0x10'
>>> hex(10)
'0xa'
>>> hex(18)
'0x12'
id CPython解釋器返回的是對象的內存地址, 可以很靠譜的來判斷已存在的對象是否一致
>>> id(1)
4305218368
isinstance 用於判斷一個類的實例是否是它的子類
>>> isinstance((1,2), tuple)
True
>>> isinstance((1,2), list)
False
issubclass 判斷一個類是否是另一個類的子類或相同類 issubclass(x, (A, B, …)) 等同於 issubclass(x, A) or issubclass(x, B) or …
>>> issubclass(dict, dict)
True
>>> issubclass(dict, (int, dict))
True
iter 傳入一個可迭代對象,返回一個迭代器
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

>>> iter([1,2])
<list_iterator object at 0x1044b10f0>
len 返回一個容器中元素的數量,比如list, dict 等
>>> len(range(2,5))
3
locals 以dict的形式返回當前環境中的局部變量
max 返回最大值, 若可迭代對象是空,則返回default值
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value

>>> max(1,5,2,7)
7
>>> max([],default=10)
10
min 返回最小值, 若可迭代對象是空,則返回default值
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

>>> min([],default=10)
10
>>> min(1,5,2,7)
1
next(iterator[, default]) 返回可迭代對象的下個元素,若設置了default值,則在迭代器耗盡的時候返回default值,否則拋出StopIteration異常
>>> a = iter([1,2,3])
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> a = iter([1,2,3])
>>> next(a, 9)
1
>>> next(a, 9)
2
>>> next(a, 9)
3
>>> next(a, 9)
9
oct 返回一個整數的八進制
>>> oct(1)
'0o1'
>>> oct(8)
'0o10'
>>> oct(9)
'0o11'
ord 返回一個字符串長度的 Unicode 編碼

ord() 是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,它以一個字符(長度爲1的字符串)作爲參數,返回對應的 ASCII 數值,或者 Unicode 數值,如果所給的 Unicode 字符超出了你的 Python 定義範圍,則會引發一個 TypeError 的異常。

>>> ord('1')
49
>>> ord('15')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
pow 若傳入兩個參數,等同於xy;若傳入三個參數,等同於xy % z
>>> pow(2,3)
8
>>> pow(2,3,5)
3
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) 用於打印輸出

print 在 Python3.x 是一個函數,但在 Python2.x 版本不是一個函數,只是一個關鍵字。

參數
objects -- 複數,表示可以一次輸出多個對象。輸出多個對象時,需要用 , 分隔。
sep -- 用來間隔多個對象,默認值是一個空格。
end -- 用來設定以什麼結尾。默認值是換行符 \n,我們可以換成其他字符串。
file -- 要寫入的文件對象。

>>> print('test')
test
>>> print('test', 1,2)
test 1 2
repr 將對象轉化爲供解釋器讀取的形式
>>> repr(1)
'1'
>>> repr({'a':1})
"{'a': 1}"
round 返回浮點數x的四捨五入值

ndigits 可能是負數

>>> round(1.23)
1
>>> round(1.73)
2
>>> round(-1.73)
-2
>>> round(-1.13)
-1
>>> round(-0.9)
-1
setattr(object, name, value) 爲一個對象設置屬性,可以對已存在的屬性進行賦值或新增屬性

setattr(x, ‘y’, v) 和 x.y = v 等價

>>>class A():
...     name = "小明"
... 
>>> a = A()
>>> setattr(a, "age", 5)
>>> print(a.age)
5
sorted(iterable, key=None, reverse=False) 返回可迭代的對象的排序列表

sort 與 sorted 區別:

  • sort 是應用在 list 上的方法,sorted 可以對所有可迭代的對象進行排序操作。
    list 的 sort 方法返回的是對已經存在的列表進行操作,無返回值.
  • 內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。
參數說明:
iterable -- 可迭代對象。
key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(默認)。

# sort 原來的列表發生了變化
>>> a = [5,4,3]
>>> a.sort()
>>> a
[3, 4, 5]

# sort 原來的列表不變
>>> a = [5,4,3]
>>> sorted(a)
[3, 4, 5]
>>> a
[5, 4, 3]

# 利用key
>>> sorted([('b', 2), ('d', 4),('a', 1),('c', 3)],key=lambda x:x[1])
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
sum 返回可迭代對象中的數字的總和, 默認爲從0開始加
>>> sum([1,2,3])
6
>>> sum([])
0
vars(p_object=None) 返回對象object的屬性和屬性值的字典對象。 不帶參數等同於locals(), 帶參數等同於object.dict.
>>> vars()
{'__name__': '__main__', '__spec__': None, '__doc__': None, 'a': [5, 4, 3], '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

>>> vars(dict)
mappingproxy({'__contains__': <method '__contains__' of 'dict' objects>, '__ge__': <slot wrapper '__ge__' of 'dict' objects>, '__init__': <slot wrapper '__init__' of 'dict' objects>, 'fromkeys': <method 'fromkeys' of 'dict' objects>, '__len__': <slot wrapper '__len__' of 'dict' objects>, '__doc__': "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n    (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n    d = {}\n    for k, v in iterable:\n        d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n    in the keyword argument list.  For example:  dict(one=1, two=2)", '__sizeof__': <method '__sizeof__' of 'dict' objects>, 'copy': <method 'copy' of 'dict' objects>, '__lt__': <slot wrapper '__lt__' of 'dict' objects>, 'update': <method 'update' of 'dict' objects>, 'pop': <method 'pop' of 'dict' objects>, '__eq__': <slot wrapper '__eq__' of 'dict' objects>, '__le__': <slot wrapper '__le__' of 'dict' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'dict' objects>, '__iter__': <slot wrapper '__iter__' of 'dict' objects>, 'popitem': <method 'popitem' of 'dict' objects>, 'items': <method 'items' of 'dict' objects>, '__gt__': <slot wrapper '__gt__' of 'dict' objects>, '__hash__': None, 'clear': <method 'clear' of 'dict' objects>, 'get': <method 'get' of 'dict' objects>, '__repr__': <slot wrapper '__repr__' of 'dict' objects>, '__ne__': <slot wrapper '__ne__' of 'dict' objects>, 'setdefault': <method 'setdefault' of 'dict' objects>, '__new__': <built-in method __new__ of type object at 0x100976960>, '__setitem__': <slot wrapper '__setitem__' of 'dict' objects>, 'keys': <method 'keys' of 'dict' objects>, '__getitem__': <method '__getitem__' of 'dict' objects>, '__delitem__': <slot wrapper '__delitem__' of 'dict' objects>, 'values': <method 'values' of 'dict' objects>})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章