日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python3 内置函数详解

發(fā)布時(shí)間:2024/10/12 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3 内置函数详解 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

內(nèi)置函數(shù)詳解

abs(x)

返回?cái)?shù)字的絕對(duì)值,參數(shù)可以是整數(shù)或浮點(diǎn)數(shù),如果參數(shù)是復(fù)數(shù),則返回其大小。

# 如果參數(shù)是復(fù)數(shù),則返回其大小。>>> abs(-25) 25>>> abs(25) 25

all(iterable)

all()會(huì)循環(huán)括號(hào)內(nèi)的每一個(gè)元素,如果括號(hào)內(nèi)的所有元素都是真的,或者如果iterable為空,則返回True,如果有一個(gè)為假的那么就返回False

>>> all([]) True >>> all([1,2,3]) True >>> all([1,2,""]) False # 如果有一個(gè)為假,則都為假 >>> all([1,2,None]) False

假的參數(shù)有:False、0、None、""、[]、()、{}等,查看一個(gè)元素是否為假可以使用bool進(jìn)行查看。

any(iterable)

循環(huán)元素,如果有一個(gè)元素為真,那么就返回True,否則就返回False

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

ascii(object)

在對(duì)象的類中尋找__repr__方法,獲取返回值

>>> class Foo:... def __repr__(self):... return "hello"...>>> obj = Foo()>>> r = ascii(obj)>>> print(r) # 返回的就是__repr__的返回值,只能是字符串 <__main__.Foo object at 0x000001FDEE13D320>

bin(x)

將整數(shù)x轉(zhuǎn)換為二進(jìn)制字符串,如果x不為Python中int類型,x必須包含方法__index__()并且返回值為integer

# 返回一個(gè)整數(shù)的二進(jìn)制>>> bin(999) '0b1111100111'# 非整型的情況,必須包含__index__()方法切返回值為integer的類型>>> class myType:... def __index__(self):... return 35...>>> myvar = myType()>>> bin(myvar) '0b100011'

bool([x])

查看一個(gè)元素的布爾值,非真即假

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

bytearray([source [, encoding [, errors]]])

返回一個(gè)byte數(shù)組,Bytearray類型是一個(gè)可變的序列,并且序列中的元素的取值范圍為 [0 ,255]。
source參數(shù):

  • 如果source為整數(shù),則返回一個(gè)長(zhǎng)度為source的初始化數(shù)組;
  • 如果source為字符串,則按照指定的encoding將字符串轉(zhuǎn)換為字節(jié)序列;
  • 如果source為可迭代類型,則元素必須為[0 ,255]中的整數(shù);
  • 如果source為與buffer接口一致的對(duì)象,則此對(duì)象也可以被用于初始化bytearray;
  • >>> bytearray(3) bytearray(b'\x00\x00\x00')

    bytes([source[, encoding[, errors]]])

    >>> bytes("asdasd",encoding="utf-8") b'asdasd'

    callable(object)

    返回一個(gè)對(duì)象是否可以被執(zhí)行

    >>> def func():... return 123...>>> callable(func) True>>> func = 123>>> callable(func) False

    chr(i)

    返回一個(gè)數(shù)字在ASCII編碼中對(duì)應(yīng)的字符,取值范圍256個(gè)

    >>> chr(66) 'B'>>> chr(5) '\x05'>>> chr(55) '7'>>> chr(255) '\xff'>>> chr(25) '\x19'>>> chr(65) 'A'

    classmethod(function)

    返回函數(shù)的類方法

    compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

    把字符串編譯成python可執(zhí)行的代碼

    >>> str = "for i in range(0,10): print(i)">>> c = compile(str,'','exec')>>> exec(c) 0 1 2 3 4 5 6 7 8 9

    complex([real[, imag]])

    創(chuàng)建一個(gè)值為real + imag * j的復(fù)數(shù)或者轉(zhuǎn)化一個(gè)字符串或數(shù)為復(fù)數(shù)。如果第一個(gè)參數(shù)為字符串,則不需要指定第二個(gè)參數(shù)

    >>> complex(1, 2) (1+2j) # 數(shù)字>>> complex(1) (1+0j) # 當(dāng)做字符串處理>>> complex("1") (1+0j) # 注意:這個(gè)地方在“+”號(hào)兩邊不能有空格,也就是不能寫成"1 + 2j",應(yīng)該是"1+2j",否則會(huì)報(bào)錯(cuò)>>> complex("1+2j") (1+2j)

    delattr(object, name)

    刪除對(duì)象的屬性值

    >>> class cls: ... @classmethod ... def echo(self): ... print('CLS') ... >>> cls.echo() CLS >>> delattr(cls, 'echo') >>> cls.echo() Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: type object 'cls' has no attribute 'echo'

    dict(**kwarg)

    創(chuàng)建一個(gè)數(shù)據(jù)類型為字典

    >>> dic = dict({"k1":"123","k2":"456"})>>> dic {'k1': '123', 'k2': '456'}

    dir([object])

    返回一個(gè)對(duì)象中中的所有方法

    >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce\_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

    divmod(a, b)

    返回的是a//b(除法取整)以及a對(duì)b的余數(shù),返回結(jié)果類型為tuple

    >>> divmod(10, 3) (3, 1)

    enumerate(iterable, start=0)

    為元素生成下標(biāo)

    >>> li = ["a","b","c"]>>> for n,k in enumerate(li):... print(n,k)... 0 a 1 b 2 c

    eval(expression, globals=None, locals=None)

    把一個(gè)字符串當(dāng)作一個(gè)表達(dá)式去執(zhí)行

    >>> string = "1 + 3">>> string '1 + 3'>>> eval(string) 4

    exec(object[, globals[, locals]])

    把字符串當(dāng)作python代碼執(zhí)行

    >>> exec("for n in range(5): print(n)") 0 1 2 3 4

    filter(function, iterable)

    篩選過濾,循環(huán)可迭代的對(duì)象,把迭代的對(duì)象當(dāng)作函數(shù)的參數(shù),如果符合條件就返回True,否則就返回False

    >>> def func(x):... if x == 11 or x == 22:... return True...>>> ret = filter(func,[11,22,33,44])>>> for n in ret:... print(n)... 11 22 >>> list(filter((lambda x: x > 0),range(-5,5))) [1, 2, 3, 4]

    float([x])

    將整數(shù)和字符串轉(zhuǎn)換成浮點(diǎn)數(shù)

    >>> float("124") 124.0>>> float("123.45") 123.45>>> float("-123.34") -123.34

    format(value[, format_spec])

    字符串格式化

    frozenset([iterable])

    frozenset是凍結(jié)的集合,它是不可變的,存在哈希值,好處是它可以作為字典的key,也可以作為其它集合的元素。缺點(diǎn)是一旦創(chuàng)建便不能更改,沒有add,remove方法。

    getattr(object, name[, default])

    返回對(duì)象的命名屬性的值,name必須是字符串,如果字符串是對(duì)象屬性之一的名稱,則結(jié)果是該屬性的值。

    globals()

    獲取或修改當(dāng)前文件內(nèi)的全局變量

    >>> a = "12" >>> bsd = "54asd" >>> globals() {'__doc__': None, 'a': '12', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'bsd': '54asd', '__builtins__': <module 'builtins' (built-in)>, 'n': '__doc__', '__name__': '__main__', '__spec__': None, '__package__': None}

    hasattr(object, name)

    參數(shù)是一個(gè)對(duì)象和一個(gè)字符串,如果字符串是對(duì)象的某個(gè)屬性的名稱,則結(jié)果為True,否則為False。

    hash(object)

    返回一個(gè)對(duì)象的hash值

    >>> a = "asdadasdwqeq234sdfdf">>> hash(a) 5390438057823015497

    help([object])

    查看一個(gè)類的所有詳細(xì)方法,或者查看某個(gè)方法的使用詳細(xì)信息

    >>> help(list) Help on class list in module __builtin__:class list(object)| list() -> new empty list| list(iterable) -> new list initialized from iterable's items| | Methods defined here:| | __add__(...)| x.__add__(y) <==> x+y| | __contains__(...)| x.__contains__(y) <==> y in x| | __delitem__(...)| x.__delitem__(y) <==> del x[y]| | __delslice__(...)| x.__delslice__(i, j) <==> del x[i:j]| | Use of negative indices is not supported. ..........

    hex(x)

    獲取一個(gè)數(shù)的十六進(jìn)制

    >>> hex(13) '0xd'

    id(object)

    返回一個(gè)對(duì)象的內(nèi)存地址

    >>> a = 123>>> id(a) 1835400816

    input([prompt])

    交互式輸入

    >>> name = input("Pless your name: ") Pless your name: ansheng>>> print(name) ansheng

    int(x, base=10)

    獲取一個(gè)數(shù)的十進(jìn)制

    >>> int("31") 31

    也可以作為進(jìn)制轉(zhuǎn)換

    >>> int(10) 10>>> int('0b11',base=2) 3>>> int('11',base=8) 9>>> int('0xe',base=16) 14

    isinstance(object, classinfo)

    判斷對(duì)象是否是這個(gè)類創(chuàng)建的

    >>> li = [11,22,33] >>> isinstance(li,list) True

    issubclass(class, classinfo)

    查看一個(gè)對(duì)象是否為子類

    iter(object[, sentinel])

    創(chuàng)建一個(gè)可迭代的對(duì)象

    >>> obj = iter([11,22,33,44])>>> obj <list_iterator object at 0x000002477DB25198>>>> for n in obj:... print(n)... 11 22 33 44

    len(s)

    查看一個(gè)對(duì)象的長(zhǎng)度

    >>> url="ansheng.me">>> len(url) 10

    list([iterable])

    創(chuàng)建一個(gè)數(shù)據(jù)類型為列表

    >>> li = list([11,22,33,44])>>> li [11, 22, 33, 44]

    locals()

    返回當(dāng)前作用域的局部變量,以字典形式輸出

    >>> func()>>> def func():... name="ansheng"... print(locals())...>>> func() {'name': 'ansheng'}

    map(function, iterable, ...)

    對(duì)一個(gè)序列中的每一個(gè)元素都傳到函數(shù)中執(zhí)行并返回

    >>> list(map((lambda x : x +10),[1,2,3,4])) [11, 12, 13, 14]

    max(iterable, *[, key, default])

    max(arg1, arg2, *args[, key])

    取一個(gè)對(duì)象中的最大值

    >>> li = list([11,22,33,44]) >>> li = [11,22,33,44] >>> max(li) 44

    memoryview(obj)

    返回對(duì)象obj的內(nèi)存查看對(duì)象

    >>> import struct>>> buf = struct.pack("i"*12, *list(range(12)))>>> x = memoryview(buf)>>> y = x.cast('i', shape=[2,2,3])>>> print(y.tolist()) [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

    min(iterable, *[, key, default])

    min(arg1, arg2, *args[, key])

    取一個(gè)對(duì)象中的最小值

    >>> li = list([11,22,33,44])>>> li = [11,22,33,44]>>> min(li) 11

    next(iterator[, default])

    每次只拿取可迭代對(duì)象的一個(gè)元素

    >>> obj = iter([11,22,33,44])>>> next(obj) 11>>> next(obj) 22>>> next(obj) 33>>> next(obj) 44>>> next(obj)# 如果沒有可迭代的元素了就會(huì)報(bào)錯(cuò) Traceback (most recent call last):File "<stdin>", line 1, in <module> StopIteration

    object

    返回一個(gè)新的無特征對(duì)象

    oct(x)

    獲取一個(gè)字符串的八進(jìn)制

    >>> oct(13) '0o15'

    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

    文件操作的函數(shù),用來做文件操作的

    # 打開一個(gè)文件>>> f = open("a.txt","r")

    ord(c)

    把一個(gè)字母轉(zhuǎn)換為ASCII對(duì)對(duì)應(yīng)表中的數(shù)字

    >>> ord("a") 97>>> ord("t") 116

    pow(x, y[, z])

    返回一個(gè)數(shù)的N次方

    >>> pow(2, 10) 1024>>> pow(2, 20) 1048576

    print(*objects, sep=' ', end='n', file=sys.stdout, flush=False)

    打印輸出

    >>> print("hello word") hello word

    property(fget=None, fset=None, fdel=None, doc=None)

    range(start, stop[, step])

    生成一個(gè)序列

    >>> range(10) range(0, 10)>>> for n in range(5):... print(n)... 0 1 2 3 4

    repr(object)

    返回一個(gè)包含對(duì)象的可打印表示的字符串

    >>> repr(111) '111' >>> repr(111.11) '111.11'

    reversed(seq)

    對(duì)一個(gè)對(duì)象的元素進(jìn)行反轉(zhuǎn)

    >>> li = [1, 2, 3, 4]>>> reversed(li) <list_reverseiterator object at 0x000002CF0EF6A940>>>> for n in reversed(li):... print(n)... 4 3 2 1

    round(number[, ndigits])

    四舍五入

    >>> round(3.3) 3>>> round(3.7) 4

    set([iterable])

    創(chuàng)建一個(gè)數(shù)據(jù)類型為集合

    >>> varss = set([11,222,333])>>> type(varss) <class 'set'>

    setattr(object, name, value)

    為某個(gè)對(duì)象設(shè)置一個(gè)屬性

    slice(start, stop[, step])

    元素的切片操作都是調(diào)用的這個(gè)方法

    sorted(iterable, key)

    為一個(gè)對(duì)象的元素進(jìn)行排序

    代碼:

    #!/usr/bin/env python # _*_ coding:utf-8 _*_char=['趙',"123", "1", "25", "65","679999999999", "a","B","alex","c" ,"A", "_", "?",'a錢','孫','李',"余", '佘',"佗", "?", "銥", "鉦鉦???"]new_chat = sorted(char) print(new_chat) for i in new_chat:print(bytes(i, encoding='utf-8'))

    輸出結(jié)果:

    C:\Python35\python.exe F:/Python_code/Note/soretd.py ['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a錢', 'c', '?', '?', '佗', '佘', '余', '孫', '李', '趙', '鉦鉦???', '銥'] b'1' b'123' b'25' b'65' b'679999999999' b'A' b'B' b'_' b'a' b'alex' b'a\xe9\x92\xb1' b'c' b'\xe1\x92\xb2' b'\xe3\xbd\x99' b'\xe4\xbd\x97' b'\xe4\xbd\x98' b'\xe4\xbd\x99' b'\xe5\xad\x99' b'\xe6\x9d\x8e' b'\xe8\xb5\xb5' b'\xe9\x92\xb2\xe9\x92\xb2\xe3\xbd\x99\xe3\xbd\x99\xe3\xbd\x99' b'\xe9\x93\xb1 Process finished with exit code 0

    staticmethod(function)

    返回函數(shù)的靜態(tài)方法

    str(object=b'', encoding='utf-8', errors='strict')

    轉(zhuǎn)換成字符串

    >>> a = str(111)>>> type(a) <class 'str'>

    sum(iterable[, start])

    求和

    >>> sum([11,22,33]) 66

    super([type[, object-or-type]])

    執(zhí)行父類的構(gòu)造方法

    tuple([iterable])

    創(chuàng)建一個(gè)對(duì)象,數(shù)據(jù)類型為元組

    >>> tup = tuple([11,22,33,44]) >>> type(tup) <class 'tuple'>

    type(object)

    查看一個(gè)對(duì)象的數(shù)據(jù)類型

    >>> a = 1>>> type(a) <class 'int'>>>> a = "str">>> type(a) <class 'str

    vars([object])

    查看一個(gè)對(duì)象里面有多少個(gè)變量

    zip(*iterables)

    將兩個(gè)元素相同的序列轉(zhuǎn)換為字典

    >>> li1 = ["k1","k2","k3"] >>> li2 = ["a","b","c"] >>> d = dict(zip(li1,li2)) >>> d {'k1': 'a', 'k2': 'b', 'k3': 'c'}

    import(name, globals=None, locals=None, fromlist=(), level=0)

    導(dǎo)入模塊,把導(dǎo)入的模塊作為一個(gè)別名

    轉(zhuǎn)載于:https://www.cnblogs.com/guigujun/p/7614888.html

    總結(jié)

    以上是生活随笔為你收集整理的python3 内置函数详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。