程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python3 內置函數

編輯:Python
"""
# 內置函數之---abs():絕對值
# a = 10086
a = 'hello'
try:
print(abs(a))
with open('666.p', 'r', encoding='utf-8') as f:
print(f.read())
except TypeError:
print('Error: 數據類型錯誤')
except IOError:
print('文件打開失敗')
else:
print(666)
finally:
print(222)
"""
"""
# 內置函數之---divmod():把除數和余數運算結果結合起來,返回一個包含商和余數的元組(a // b, a % b)。被除數 除數 商 余數
print(divmod(45, 4))
print(45 / 4)
print(45 // 4)
print(45 % 4)
"""
"""
# 內置函數之---input():接受一個標准輸入數據,返回為 string 類型。
x = input('請輸入一個字符串: ')
print(x)
print(type(x))
"""
"""
# 內置函數之---open(): 函數用於打開一個文件,創建一個 file 對象,相關的方法才可以調用它進行讀寫。
# f = open('../run.py', 'r', encoding='utf-8')
# s = f.read()
# f.close()
# print(s)
# with open('../run.py', 'r', encoding='utf-8') as f:
# s = f.read()
# print(s)
"""
"""
# 內置函數之---staticmethod(): 返回函數的靜態方法。
class testStaticMethod(object):
@staticmethod
def play():
print('靜態方法')
def song(self):
print('普通方法')
# classmethod 修飾符對應的函數不需要實例化,不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數,可以來調用類的屬性,類的方法,實例化對象等。
@classmethod
def runs(cls):
print('類方法')
print(cls)
# 類的實例調用
# testStaticMethod().play()
# testStaticMethod().song()
# testStaticMethod().runs()
# 類的靜態調用
testStaticMethod.runs()
testStaticMethod.play()
# testStaticMethod.song() # 報錯, 普通方法不能靜態調用,會報錯
"""
'''
# 內置函數之---all(): 用於判斷給定的可迭代參數 iterable 中的所有元素是否都為 TRUE,如果是返回 True,否則返回 False。
print(all([1, 2, 3]))
print(all([0, 1, 2, 3]))
'''
'''
# 內置函數之---enumerate(): 用於將一個可遍歷的數據對象(如列表、元組或字符串)組合為一個索引序列,同時列出數據和數據下標,一般用在 for 循環當中
lst = ['小米', '華為', 'oppo', 'vivo', '蘋果']
# 方式一:
# for i in lst:
# print(i)
# 方式二:
# for i in range(len(lst)):
# print(i, lst[i])
# 方式三:
# enumerate(): 枚舉
# for i in enumerate(lst):
# print(i)
# 方式四:
start = 100
for k, v in enumerate(lst, start): # start可省略,默認是0, k,v---解包
print(k, '====', v)
'''
'''
# 內置函數之---int():
x = '78'
# print(x)
# print(type(x))
print(int(x))
print(type(int(x)))
'''
"""
# 內置函數之---ord():ord() 函數是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,它以一個字符(長度為1的字符串)作為參數,返回對應的 ASCII 數值,或者 Unicode 數值,如果所給的 Unicode 字符超出了你的 Python 定義范圍,則會引發一個 TypeError 的異常。
print(ord('a')) # 97
print(ord('A')) # 65
print(chr(97)) # a
print(chr(65)) # A
"""
"""
# 內置函數之---str():將其他對象轉化為字符串。
lst = ['apple', 'huawei']
print(str(lst))
print(type(str(lst)))
"""
'''
# 內置函數之---any():用於判斷給定的可迭代參數 iterable 是否全部為 False,則返回 False,如果有一個為 True,則返回 True。
lst = ['', None, "", False]
lst1 = ['', None, "", False, 1]
print(any(lst))
print(any(lst1))
'''
"""
# 內置函數之----eval():用來執行一個字符串表達式,並返回表達式的值。用來執行一段python代碼
eval('print(666)')
"""
"""
# 內置函數之----isinstance():判斷一個對象是否是一個已知的類型,類似 type()。
s = 'abc'
print(isinstance(s, str))
number = 5
print(isinstance(number, int))
print(isinstance(s, (str, int, tuple, list, dict, set)))
"""
"""
# 內置函數之---pow(x,y): 返回 x的y次方 的值。
print(pow(2, 3))
print(pow(2, 5))
# 等價於: print(2 ** 3)
"""
'''
# 內置函數之---sum(): 對系列進行求和計算。
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
lst3 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(sum(lst))
print(sum(lst2))
print(sum(lst3))
'''
# 內置函數之---ascii(): 函數類似 repr() 函數, 返回一個表示對象的字符串, 但是對於字符串中的非 ASCII 字符則返回通過 repr() 函數使用 \x, \u 或 \U 編碼的字符。 生成字符串類似 Python2 版本中 repr() 函數的返回值。
"""
# 內置函數之---bin() 返回一個整數 int 或者長整數 long int 的二進制表示。
print(bin(10))
print(bin(8))
"""
'''
# bool() 函數用於將給定參數轉換為布爾類型,如果沒有參數,返回 False。
print(bool())
print(bool(0))
print(bool(1))
print(bool('abc'))
print(bool(False))
print(bool(True))
'''
'''
# 內置函數之---bytearray():返回一個新字節數組。這個數組裡的元素是可變的,並且每個元素的值范圍: 0 <= x < 256。
# print(bytearray())
# print(bytearray([1, 2, 3]))
print(bytes([1, 2, 3, 4]))
print(bytes('abc'))
'''
'''
# 內置函數之---chr(): 用一個整數作參數,返回一個對應的字符。
print(chr(97)) # a
'''
"""
# 內置函數之---compile():
# s = "for i in range(0, 10): print(i)"
# c = compile(s, '', 'exec') # 編譯為字節代碼對象
'''
lst = ['apple', 'huawei', 'xiaomi']
for i in lst:
print(i)
'''
exec('''
for i in range(6):
print(i)
''')
exec('''
lst = ['apple', 'huawei', 'xiaomi']
for i in lst:
print(i)
''')
"""
'''
# 內置函數之---filter():用於過濾序列,過濾掉不符合條件的元素,返回一個迭代器對象,如果要轉換為列表,可以使用 list() 來轉換。 該接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判,然後返回 True 或 False,最後將返回 True 的元素放到新列表中。
lst = set()
for i in range(101):
lst.add(i)
def is_even(n):
return n % 2 == 0
s = list(filter(is_even, lst))
print(s)
'''
"""
# 內置函數之---float() : 用於將整數和字符串轉換成浮點數。
print(float(12))
print(float(12.05))
print(float(-12.05))
print(float('10086'))
"""
"""
# 內置函數之---format(): 通過 {} 和 : 來代替以前的 % 。
print('{}人民{}'.format('中華', '共和國'))
print('{name}人民{country}'.format(name='中華', country='共和國'))
print('{0}{1}{2}{3}{4}{5}'.format('中華', '人民', '共和國', '中央', '人民', '政府'))
"""
'''
# 內置函數之---frozenset() 返回一個凍結的集合,凍結後集合不能再添加或刪除任何元素。
lst = ['one', 'two', 'three']
f = frozenset(lst)
print(lst)
'''
"""
# 內置函數之---getattr(): 用於返回一個對象屬性值。
class Test():
name = 'shunyuan'
def play(self):
pass
print(getattr(Test(), 'name'))
"""
"""
# 內置函數之---globals():以字典類型返回當前位置的全部全局變量。
print(globals()) # 返回全局變量
print(''.center(80, '*'))
print(locals()) # 返回當前變量(如果當前位置是全局位置,則等同於globals(),如果用在某個函數裡邊,在返回對應的函數內部的變量)
"""
"""
# 內置函數之---hasattr() : 用於判斷對象是否包含對應的屬性。
class Test():
x = 'apple'
y = 'xiaomi'
def play(self):
pass
print(hasattr(Test(), 'x'))
print(hasattr(Test(), 'y'))
print(hasattr(Test(), 'z'))
"""
'''
# 內置函數之---hash(): 獲取一個對象(字符串或者數值等)的哈希值。
print(hash('abc'))
print(hash('testadmin'))
name1='正常程序代碼'
name2='正常程序代碼帶病毒'
print(hash(name1)) # 2403189487915500087
print(hash(name2)) # -8751655075885266653
'''
"""
# 內置函數之---help(): 用於查看函數或模塊用途的詳細說明。
print(help('sys'))
print(help('os'))
print(help([1, 2, 3]))
"""
"""
# 內置函數之---hex(): 將一個指定數字轉換為 16 進制數。
print(hex(898))
"""
"""
# 內置對象之---id(): 用於獲取對象的內存地址。
print(id('abc'))
print(id(123))
"""
"""
# 內置對象之---len(): 返回對象(字符、列表、元組等)長度或項目個數。
print(len('helloworld'))
print(len([1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(len((1, 2, 3, 4, 5, 6, 7, 8, 9)))
print(len({'a', 'b', 'c', 'd'}))
print(len({'a': 'apple', 'b': 'huawei', 'c': 'xiaomi', 'd': 'oppo'}))
"""
'''
# 內置對象之---list(): 將元組或字符串轉換為列表。
print(list('abcdefg'))
print(list(('apple', 'huawei', 'xiaomi', 'oppo')))
print(list({'apple', 'huawei', 'xiaomi', 'oppo'}))
print(list({'apple1': 'ok', 'huawei1': 'error', 'xiaomi1': True, 'oppo1': False}))
'''
"""
# 內置函數之---map(): map()函數會根據提供的函數對指定序列做映射。第一個參數 function 以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表。
def square(x):
return x ** 2
res = map(square, [1, 2, 3, 4, 5, 6, 7, 8, 9])
for i in res:
print(i, end=',')
"""
'''
# 可迭代對象
# lst = ['周一', '周二', '周三', '周四', '周五']
# it = lst.__iter__() # 返回迭代器
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
'''
"""
# 內置函數之---max(): 返回給定參數的最大值,參數可以為序列。
print(max((1, 5, 85, 3, 15, 95, 20)))
print(max([1, 5, 85, 3, 15, 95, 20]))
print(max({1, 5, 85, 3, 15, 95, 20}))
# 同 min()
"""
# 內置函數之---memoryview() 函數返回給定參數的內存查看對象(Momory view)。所謂內存查看對象,是指對支持緩沖區協議的數據進行包裝,在不需要復制對象基礎上允許Python代碼訪問。
'''
# 內置函數之---iter(): 用來生成迭代器。
lst = ['a', 'b', 'c', 'd']
print(iter(lst)) # <list_iterator object at 0x0000014F7F2B24E0>
'''
"""
# 內置函數之---next(): 返回迭代器的下一個項目。
# '可迭代對象' 和 '迭代器' 不是一個概念
lst = ['huawei', 'xiaomi', 'apple', 'oppo'] # 可迭代對象
it = lst.__iter__() # 迭代器
print(next(it))
print(next(it))
print(next(it))
lst2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
it2 = iter(lst2)
print(next(it2))
print(next(it2))
print(next(it2))
print(next(it2))
"""
'''
# 內置函數之---oct(): 將一個整數轉換成8進制字符串。
print(oct(8))
'''
"""
# 內置函數之---range(): 函數返回的是一個可迭代對象(類型是對象),而不是列表類型, 所以打印的時候不會打印列表。Python3 list() 函數是對象迭代器,可以把range()返回的可迭代對象轉為一個列表,返回的變量類型為列表。
for i in range(3):
print(i, ''.center(20, '*'))
for i in list(range(3)):
print(i, ''.center(20, '+'))
print(list(range(3)))
"""
'''
# 內置函數之---reversed(): 返回一個反轉的迭代器。
# lst = 'hello world'
# lst = ('apple', 'huawei', 'xiaomi', 'oppo')
lst = ['apple', 'huawei', 'xiaomi', 'oppo']
print(list(reversed(lst)))
'''
"""
# 內置函數之---round(): 返回浮點數x的四捨五入值。
print(round(70.46895))
print(round(70.56895))
print(round(70.54895, 1))
print(round(70.55895, 1))
print(round(70.55495, 2))
print(round(70.55595, 2))
"""
"""
# 內置函數之---set(): 創建一個無序不重復元素集,可進行關系測試,刪除重復數據,還可以計算交集、差集、並集等。
# print(set(123456)) # 報錯
print(set('abcdefabcdef'))
print(set(('apple', 'huawei', 'xiaomi')))
print(set(['apple', 'huawei', 'xiaomi']))
print(set({'apple', 'huawei', 'xiaomi'}))
print(set({'first': 'apple', 'second': 'huawei', 'third': 'xiaomi'}))
"""
'''
# 內置函數之---setattr(): 對應的函數是getattr(),用於設置屬性值,該屬性不一定是存在的。
class Test():
def play(self):
pass
t = Test() # 類的實例
setattr(t, 'name', '牛頓')
print(getattr(t, 'name'))
print(t.name)
'''
"""
# 內置函數之---slice(): 實現切片對象,主要用在切片操作函數裡的參數傳遞。slice(stop) 或者 slice(start, stop[, step])
print(slice(5)) # slice(None, 5, None)
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(lst[:])
print(lst[2:])
print(lst[:5])
print(lst[0:5])
print(lst[2:5])
print(lst[::2])
print(lst[1:6:2])
print(lst[slice(2)]) # 傳遞一個參數的話就是標識的時結束位置
print(lst[slice(6)]) # 傳遞一個參數的話就是標識的時結束位置
print(lst[slice(2, 6)]) # 傳遞兩個參數的話就是標識的: 開始位置, 結束位置
print(lst[slice(2, 8, 1)]) # 傳遞兩個參數的話就是標識的: 開始位置, 結束位置
print(lst[slice(2, 8, 2)]) # 傳遞三個參數的話就是標識的: 開始位置, 結束位置, 步長
print(lst[slice(1, 9)]) # 傳遞兩個參數的話就是標識的: 開始位置, 結束位置
print(''.center(20, '*'))
print(lst[slice(-1, -8, -2)]) # 傳遞兩個參數的話就是標識的: 開始位置, 結束位置
"""
'''
# 內置函數之---sorted(): 對所有可迭代的對象進行排序操作。sort 與 sorted 區別:sort 是應用在 list 上的方法,sorted 可以對所有可迭代的對象進行排序操作。list 的 sort 方法返回的是對已經存在的列表進行操作,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。
# lst = [1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5]
# lst.sort()
# print(lst)
lst = {1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5}
print(sorted(lst))
s = 'hello world! abc ABC'
print(sorted(s))
t = (1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5)
print(sorted(t))
lst2 = [1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5]
print(sorted(lst2))
dic = {103: "xiaomi", 101: 'huawei', 102: 'apple', 104: 'vivo'}
print(sorted(dic))
'''
"""
# 內置函數之---str() 轉為字符串對象。
s = 'abc'
print(s)
print(str(s))
print(type(str(s)))
lst = ['a', 'b', 'c', 'd']
print(lst)
print(str(lst))
print(type(str(lst)))
t = ('a', 'b', 'c', 'd')
print(t)
print(str(t))
print(type(str(t)))
"""
'''
# 內置函數之---sum(): 對系列進行求和計算。
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(sum(lst))
t = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(sum(t))
se = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(sum(se))
dic = {12: 'apple', 56: 'huawei'}
print(sum(dic))
'''
"""
# 內置函數之 - --tuple(): 將列表轉換為元組。
print(tuple('abcd'))
print(tuple(['a', 'b', 'c', 'd']))
print(tuple(('a', 'b', 'c', 'd')))
print(tuple({'a', 'b', 'c', 'd'}))
print(tuple({'a': 'ok', 'b': 'error', 'c': True, 'd': False}))
"""
'''
# 內置函數之---type(): 如果你只有第一個參數則返回對象的類型,三個參數返回新的類型對象。isinstance() 與 type() 區別:type() 不會認為子類是一種父類類型,不考慮繼承關系。isinstance() 會認為子類是一種父類類型,考慮繼承關系。如果要判斷兩個類型是否相同推薦使用 isinstance()。
print(type(1))
print(type(1) == int)
'''
"""
# 內置函數之---vars() : 返回對象object的屬性和屬性值的字典對象。
class Test():
def __init__(self):
self.name = '牛頓'
self.age = 400
self.sex = '男'
def play(self):
print(vars(self))
# print(vars(Test))
Test().play()
"""
'''
# zip() 函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的對象,這樣做的好處是節約了不少的內存。我們可以使用 list() 轉換來輸出列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。
print(list(zip([100, 200, 300])))
s1 = 'abc'
s2 = 'wxyz'
print(zip(s1, s2))
print(list(zip(s1, s2)))
print(list(zip(s2, s1)))
lst1 = ['first', 'second', 'third']
lst2 = ['xiaomi', 'huawei', 'apple']
print(zip(lst1, lst2))
print(list(zip(lst1, lst2)))
t1 = ('first', 'second', 'third')
t2 = ('xiaomi', 'huawei', 'apple')
print(zip(t1, t2))
print(list(zip(t1, t2)))
se1 = {'first', 'second', 'third'}
se2 = {'xiaomi', 'huawei', 'apple'}
print(list(zip(se1, se2)))
dic1 = {'first': 100, 'second': 200, 'third': 300}
dic2 = {'huawei': 111, 'xiaomi': 222, 'apple': 333}
print(list(zip(dic1, dic2)))
'''
"""
# 形參參數的傳遞: *args---接受位置參數, **kwargs---接受關鍵字參數; 其中,位置參數在前,關鍵字參數在後. *args和**kwargs有是參數聚合的意思
def func(*args, **kwargs):
print(args) # 元組類型
print(kwargs) # 字典類型
# func('apple', 'huawei', 'xiaomi', name='牛頓', age=400, sex='男')
# 實參參數的傳遞: 如果實際參數前面加了一個'*'號,表示打散位置參數; 如果加了兩個'**'號碼,表示打散關鍵字參數; 其中: 打散位置參數時,除了int類型外,其他類型都可以; 打散關鍵字參數時,只能是字典類型的
func(*'apple', *{'first', 'second', 'third'}, *['sex', 'age', 'name'], *('good', 'bad', 'error', 'success'),
*{'one': True, 'two': False}, **{'car': '奔馳', 'price': '100萬'})
"""
'''
# 打包壓縮
a = [1, 2, 3]
b = ['蘋果', '華為', '小米']
c = ['one', 'two', 'third']
d = ['sex', 'name', 'age']
print(list(zip(a, b, c, d))) # 由元組組成的列表
m, n, p = zip(a, b, c, d)
print(m)
print(n)
print(p)
# 解構(解包)
x, y = zip(*[(1, '蘋果'), (2, '華為'), (3, '小米')])
print(x)
print(y)
'''

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved