Python 3大常用内蔵関数
3635 ワード
2020年11月下旬に整理し、平凡に甘んじないあなたにもっとpython 3の基礎知識を捧げます.
https://blog.csdn.net/weixin_45316122/article/details/109843899
Trick:純demo、心はどこにあるのか、結果はそこにある.
1.sorted()
2.map()
3.enumerate()
4.zip()
5.filter()
6.reduce()
https://blog.csdn.net/weixin_45316122/article/details/109843899
Trick:純demo、心はどこにあるのか、結果はそこにある.
1.sorted()
2.map()
3.enumerate()
4.zip()
5.filter()
6.reduce()
# -*- coding: utf-8 -*-
# Author : szy
#1.sorted()
"""
builtins
def sorted(iterable: Iterable[_T],
*,
key: Optional[(_T) -> Any] = ...,
reverse: bool = ...) -> List[_T]
"""
# 1)
sorted([100, 98, 102, 1, 40])
# Out[2]: [1, 40, 98, 100, 102]
# 2) key /
# ,
L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]
new_line=sorted(L,key=lambda x:len(x))
# Out[5]: [{1: 9}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}]
# 3) tuple List ( python )
students = [('wang', 'A', 15), ('li', 'B', 12), ('zhang', 'B', 10)]
sorted(students, key=lambda student : student[2])#student[2]
# 4) cmp python3 cmp
# #TypeError: 'cmp' is an invalid keyword argument for this function
from functools import cmp_to_key
nums = [4, 3, 2, 1]
sorted(nums,key=cmp_to_key(lambda a, b: a - b))
"------------------------------ ------------------------------"
# 2.map()
"""
builtins
@overload def map(func: (...) -> _S,
iter1: Iterable,
iter2: Iterable,
iter3: Iterable,
iter4: Iterable,
iter5: Iterable,
iter6: Iterable,
*iterables: Iterable) -> Iterator[_S]
"""
# map , f list, f list
# list,map . ( )。
# list [None, None, None, None, None, None, None, None, None]
def f(x):
return x*x
map(f,[1,2,3,4,5])
# 3.enumerate()
"""
enumerate
def __init__(self,
iterable: Iterable[_T],
start: int = ...) -> None
"""
# enumerate() ( 、 ) , , for 。
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
pass
# print(i, seq[i])
#0 one
# 1 two
# 2 three
" , 。"
# 4.zip()
"""
builtins ( )
@overload def zip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]
"""
# zip ( 0 1 ) , tuple
nums = ['flower','flow','flight']
for i in zip(*nums):
pass
# print(i)
# ('f', 'f', 'f')
# ('l', 'l', 'l')
# ('o', 'o', 'i')
# ('w', 'w', 'g')
# 5)filter()'
"""
builtins
@overload def filter(function: (_T) -> Any,
iterable: Iterable[_T]) -> Iterator[_T]
"""
# , , , , list() 。
# , , , , True False, True 。
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
# print(newlist)
# [1, 3, 5, 7, 9]
# 6)reduce()
'''
No documentation found. python3
from functools import reduce
'''
# reduce() 。
# ( , )
# : reduce function( ) 1、2 , function , 。
from functools import reduce
def add(x, y) : #
return x + y
reduce(add, [1,2,3,4,5]) # :1+2+3+4+5
reduce(lambda x, y: x+y, [1,2,3,4,5]) # lambda
# 15