Python—內置函數

內置函數html

內置函數補充python


 all: 全部iterable類型,包含的元素要全爲真才返回真shell

>>> all([0,-1,5])
False
>>> all([-1,5])
True

any:有iterable類型,非空且包含任一爲真element就返回trueapi

>>> any([])
False
>>> any([0])
False
>>> any([0,12])
True

ascii:app

>>> a = ascii([1,2,"中文"])   
>>> print(type(a),[a])
<class 'str'> ["[1, 2, '\\u4e2d\\u6587']"]
>>> #把內存的數據轉換爲可打印的字符串格式

bin:python2.7

>>> bin(2)  #把十進制轉換爲二進制
'0b10'
>>> #convert an integer number to a binary string ,須要整數才能轉
#二進制轉十進制
>>> int('0b10',2)  #若是前面有標識進制數,後面不用加 base
2
>>> int('10',base=2)
2
>>> int('0x10',16)
16
>>> int('0o657',8)
431
>>> int('657',base=8)
431
>>> bin(431)
'0b110101111'
>>> oct(431)
'0o657'
>>> hex(431)
'0x1af'
>>> 
2,8,16,10進制互轉

bool:判斷真假ssh

>>> bool([])     
False
>>> bool(0)     
False
>>> bool([0,1])
True

bytes:轉換爲二進制格式ide

>>> a = bytes("abcde",encoding='utf-8')
>>> print(a.capitalize(),a)
b'Abcde' b'abcde'
>>> a[0]
97
>>> a[0] = 100    #當想修改它時會報錯
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a[0] = 100
TypeError: 'bytes' object does not support item assignment
>>> 

bytearray:函數

>>> b = bytearray("abcde",encoding='utf-8')
>>> b[0]
97
>>> b[0] = 102
>>> print(b)
bytearray(b'fbcde')
>>> #bytearray變成變成二進制列表的形式,並能夠修改,不多用到

callable:網站

>>> print(callable([]))
False
>>> #判斷是否能夠調用,後面能加括號的就是能調用的,好比函數
>>> def sayhi():
    pass
>>> callable(sayhi())  #此時爲函數運行結果,不能調用
False
>>> callable(sayhi) #注意此時函數爲內存地址,能夠調用
True

chr:

>>> chr(87) #把Unicode中的數字對應的元素返回出來
'W'

ord:

>> ord('a') #把元素返回爲Unicode中對應的數字號碼
97

compile:#compile(str,'err.log','exec or eval') 把字符串編譯爲可運行的代碼

>>> code = 'for i in range(2):print(i)'
>>> compile(code,'','exec')
<code object <module> at 0x000001C8899C89C0, file "", line 1>
>>> exec(code)  #至關於import了這個模塊,而後執行 >>>>
0
1
2

dict:

>>>dict() # 建立空字典 {} 
>>> dict(a='a', b='b', t='t')             # 傳入關鍵字 {'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函數方式來構造字典 {'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代對象方式來構造字典 {'three': 3, 'two': 2, 'one': 1} >>>

delattr :

很重要,先跳過

dir:

>>> a = {}
>>> dir(a)  #查可用方法
['__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__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> 

divmod:

divmod(5,2)  # 5除以2 並返回商和餘數
(2, 1)

lambda: 匿名函數

>>> x = lambda n:3 if n<3 else n
>>> x(7)  #>>> x(2) 輸出爲 3
7

>>>aaa = lambda x,y:x+y
>>>print(aaa(1,2)) #定義了幾個參數就傳幾個參數和函數同樣
3

format:

實例
>>>"{} {}".format("hello", "world")    # 不設置指定位置,按默認順序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 設置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 設置指定位置
'world hello world'
也能夠設置參數:

實例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))
 
# 經過字典設置參數
site = {"name": "菜鳥教程", "url": "www.runoob.com"}
print("網站名:{name}, 地址 {url}".format(**site))
 
# 經過列表索引設置參數
my_list = ['菜鳥教程', 'www.runoob.com']
print("網站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必須的
format

 

filter:過濾

>>> res = filter(lambda n:n>5,range(10))     #filter(function,iterable),參數1爲條件,參數2爲可迭代類型 >>> for i in res:
    print(i)

6
7
8
9
>>> #在range(10)中過濾出大於5的元素

map:   map(function,iterable),按照function的功能,對iterable進行操做

>>> res2 = map(lambda n:n*n,range(3))
>>> for i in res2:
    print(i)

0
1
4
>>> #map(function,iterable),按照function的功能,對iterable進行操做
>>> #是個迭代器,要用for循環輸出
>>> #和列表生成式同樣,區別是map是迭代器

reduce : 在python3中不是內置函數,須要import  functools調用

>>> import functools
>>> res3 = functools.reduce(lambda x,y:x+y,range(10))
>>> print(res3)
45
>>> #x爲返回值,y爲第一個數,執行x+y後,x變爲x+y,y變爲下一個數,從而獲得從1加到10的值
>>> #在python2.7中 reduce爲內置函數,如今要用functools導入調用

float:  將數字或者字符串,返回爲浮點數

>>> float(3)
3.0
>>> float('3.4')
3.4

 globals(): 只打印全局變量   locals():打印局部變量

>>> a = [1]
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': [1]}
>>> globals().get('a')
[1]
>>> #golbals 變量名是key,變量值是value,返回當前程序全部的變量

 

frozenset():

>>> set1 = frozenset([1,4,4,3])
>>> 不可變集合,用這個定義集合後,set1
SyntaxError: invalid character in identifier
>>> #不可變集合,用這個定義集合後,set1就不可變,pop,clear方法都沒了

hash():

>>> hash('gkx')  #返回對象的哈希值
-3746276222014687951
>>> #能夠應用於數字、字符串和對象,不能直接應用於 list、set、dictionary。

help(),hex(),int(),isinstance(),len(),list(),iter()

>>> help(a.append)   #返回幫助信息
Help on built-in function append:
append(...) method of builtins.list instance
    L.append(object) -> None -- append object to end

>>> hex(66) '0x42'
>>> #轉十六機制     bin()#轉二進制   oct() #轉八進制

>>> id(a) 1960805134216
>>> #返回內存地址

>>> int(3.4)  
3
>>> int('3')  #返回整數,注意'3.4'字符串若是時小數,返回會報錯
3

>>> iter([]) #變爲iterator
<list_iterator object at 0x000001C889A4C908>

>>> a = 'abc'
>>> len(a)  #查詢變量長度
3
>>> a = list() >>> #定義一個列表

 max()  min() : #1,比較的元素是可迭代對象,用for循環原理,若是第一個元素分出大小,後面就不會繼續比較了。2.根據ASCII碼值的大小比較

>>> max([2,3,45])  #求最大值
45
>>> min([2,3,45])  #求最小值
2

next():

>>> next(iter([1,2,3]))
1
>>> #返回迭代器的下一個元素

pow():

>>> pow(3,3)
27
>>> #返回3的3次方

repr():

>>> a = [1,2,3]
>>> repr(a)
'[1, 2, 3]'
>>> #相似ascii,轉爲str

round():

>>> round(1.33333,2)
1.33
>>> #保留小數位,根據參數2.  默認是保留整數位

slice(起始位置,終止位置,間距):  list的切片方法 【:】如出一轍

>>> d = 'abcde'
>>> c = [1,2,3,4,5]
>>> d[slice(1,2)]
'b'
>>> d[slice(4)]
'abcd'
>>> #切片
>>> d = range(10)
>>> d[slice(2,5)]
range(2, 5)
>>> #slice(起始位置,結束位置,間距)
>>> d[2:5]
range(2, 5)
>>> 
View Code

sorted():

>>> a = {1:2,3:6,7:11,-1:6}
>>> sorted(a.items())  #默認用key排序
[(-1, 6), (1, 2), (3, 6), (7, 11)]
>>> sorted(a.items(),key=lambda x:x[1])  #用value排序,用到匿名函數
[(1, 2), (3, 6), (-1, 6), (7, 11)]
>>> 

sum():求和

>>> sum([1,2,3,4])
10

tuple(): 定義一個元組

>>> a = tuple()
>>> a
()

zip():

>>> cc = ['gkx','lion','cat']
>>> dd = [1,2,3]
>>> for i in zip(cc,dd):  #由於是一個迭代器,因此要用循環
    print(i)

('gkx', 1)
('lion', 2)
('cat', 3)
>>> 
>>> dd = [1,2,3,4,5]
>>> for i in zip(cc,dd):
    print(i)

('gkx', 1)
('lion', 2)
('cat', 3)
>>> #按最小的拼接
View Code
>>>dict()                        # 建立空字典
{}
>>> dict(a='a', b='b', t='t')     # 傳入關鍵字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # 映射函數方式來構造字典
{'three': 3, 'two': 2, 'one': 1} 
>>> dict([('one', 1), ('two', 2), ('three', 3)])    # 可迭代對象方式來構造字典
{'three': 3, 'two': 2, 'one': 1}
>>>

 

 

__import__():

import sys  
__import__('a')        # 導入 a.py 模塊
相關文章
相關標籤/搜索