Python3中內置函數

目錄

1:查看內置函數及函數說明

2:內置函數

2.1 map

2.2 filter

2.3 zip

2.4 sorted 排序


1:查看內置函數及函數說明

Python3中有哪些內置函數呢?可以使用下面代碼查看:

print([item for item in dir(__builtins__) if not item.startswith('__') and   item[0].islower() ])

"""
結果:
['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 
'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 
'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 
'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance',
 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range',
 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 
'sum', 'super', 'tuple', 'type', 'vars', 'zip']
"""

如果不知道某個函數怎麼用,怎麼辦? 使用help函數查看:

print(help(abs))
'''
abs(x, /)
    Return the absolute value of the argument.
'''

print(help(all))
'''
all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.
'''


print(help(any))
'''
any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.
'''

2:內置函數

2.1 map

print(help(map))

'''
class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
  ......


'''

意思就是把後面可迭代對象中每個元素傳遞給func處理:

lst1 = [1,2,3]
lst2 = [4,5,6]

# 一個參數,對應後面一個可以迭代對象
ret = list(map(lambda x: x **2,lst1))
print(ret)  # [1, 4, 9]

# 兩個參數,對應後面兩個可以迭代對象
ret = list(map(lambda x,y:x+y + 10,lst1,lst2))
print(ret) # [15, 17, 19]

2.2 filter

print(help(filter))
'''

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
    ......

'''

對後面可迭代對象中的每個元素,調用前面的函數處理,如果處理結果爲True,那麼這個元素會保留下來,否則會被過濾掉;

如果前面函數傳遞是None,那麼會把可迭代對象中爲真的值保留下來。

lst1 = [0,1,2,3,4,5,6,7,8,9]


def f(x):
	return x % 3 == 0

# 使用普通函數 
ret = list(filter(f,lst1))
print(ret)  # [0, 3, 6, 9]

# 使用匿名函數
ret = list(filter(lambda x:x % 3 == 0,lst1))
print(ret)  # [0, 3, 6, 9]

lst2 = [0,4,None,5,6,{},[1,2,3,0]]
ret = list(filter(None,lst2))
print(ret)  # [4, 5, 6, [1, 2, 3, 0]]    只是作用於頂層元素

2.3 zip

print(help(zip))

"""
class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
    ......
 |  
"""

示例:

lst1 = [1,2,3]
lst2 = [4,5,6,14]
lst3 = [7,8,9,17,18]
z = zip(lst1,lst2,lst3)
print(list(z))   #  輸出: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 

# 自己實現的zip
def myzip(*seqs):
	seqs = [list(s) for s in seqs]
	res = []
	while all(seqs):
		res.append( tuple(s.pop(0) for s in seqs   ))
	return res
lst1 = [1,2,3]
lst2 = [4,5,6,14]
lst3 = [7,8,9,17,18]
z = myzip(lst1,lst2,lst3)

print(list(z))  # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

2.4 sorted 排序

print(help(sorted))

"""
sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
"""

參數說明:
iterable:是可迭代類型;
key:傳入一個函數名,函數的參數是可迭代類型中的每一項,根據函數的返回值大小排序;
reverse:排序規則. reverse = True  降序 或者 reverse = False 升序,有默認值。
返回值:有序列表

lst = [3,1,44,5,11,90]
print(lst)

# 降序
lst2= sorted(lst,reverse = True)
print(lst2)  # [90, 44, 11, 5, 3, 1]

# 升序(默認的) 
lst2= sorted(lst)
print(lst2)  # [1, 3, 5, 11, 44, 90]

lst = [3,1,44,-5,11,-90]
# 按照元素的絕對值來排序,降序
lst2= sorted(lst,key=abs,reverse = True)
print(lst2)  # [-90, 44, 11, -5, 3, 1]


lst = [3,1,44,-5,11,-90]
# 使用匿名函數,降序
lst2= sorted(lst,key=lambda x:x if x >= 0 else -x,reverse = True)
print(lst2)  # [-90, 44, 11, -5, 3, 1]

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章