先来看一段代码
lst = list()
for i in range(5):
lst.append(i)
print(lst)
运行结果:
[0, 1, 2, 3, 4]
lst = [i for i in range(5)]
print(lst)
运行结果:
[0, 1, 2, 3, 4]
循环模式:
[元素 for 元素 in 可迭代对象]
lst = [i for i in range(5)]
print(lst)
运行结果:
[0, 1, 2, 3, 4]
筛选模式
筛选模式:
[元素 for 变量 in 可迭代对象 if 条件]
lst = [i for i in range(5) if i > 2]
print(lst)
运行结果:
[3, 4]
同理,先来看一段代码
dic = dict()
for i in range(1, 5):
dic[f"k{i}"] = i
print(dic)
运行结果:
{'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
dic = {f"k{i}": i for i in range(1, 5)}
print(dic)
运行结果:
{'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
循环模式:
{键值对 for 元素 in 可迭代对象}
dic = {f"k{i}": i for i in range(1, 5)}
print(dic)
运行结果:
{'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
筛选模式:
{键值对 for 元素 in 可迭代对象 if 条件}
dic = {f"k{i}": i for i in range(1, 5) if i > 2}
print(dic)
运行结果:
{'k3': 3, 'k4': 4}
循环模式:
{元素 for 元素 in 可迭代对象}
st = {i for i in range(5)}
print(st)
运行结果:
{0, 1, 2, 3, 4}
筛选模式:
lst = {i for i in range(5) if i > 2}
print(st)
运行结果:
{3, 4}
求字符串s = "zxdhnbhnb"
中"h"的索引
s = "zxdhnbhnb"
lst = [i for i in range(len(s)) if s[i] == "h"]
print(lst)
运行结果:
[3, 6]
将下列列表中带两个"e"的元素添加到新列表
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
lst = [name for i in names for name in i if name.count("e") == 2]
print(lst)
运行结果:
['Jefferson', 'Wesley', 'Steven', 'Jennifer']
回顾一下通过函数实现生成器
return
变成yield
就变成了生成器def func():
yield 1
yield 2
yield 3
g = func()
print(next(g))
print(next(g))
print(next(g))
运行结果:
1 2 3
通过表达式实现生成器
[]
变成圆括号()
,就成了生成器表达式lst = [i for i in range(5)]
print(type(lst))
g = (i for i in range(5))
print(type(g))
运行结果:
<class 'list'>
<class 'generator'>
# g = (i for i in range(5))
def func(): # 二者等价
for i in range(5):
yield i
g= func()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
运行结果:
0 1 2 3 4
生成器表达式结构:
普通模式:
(元素 for 元素 in 可迭代对象)
g = (i for i in range(5))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
运行结果:
0 1 2 3 4
筛选模式:
(元素 for 元素 in 可迭代对象 if 条件)
g = (i for i in range(5) if i > 2)
print(next(g))
print(next(g))
运行结果:
3 4
生成器的取值方式补充:
next(生成器)
g = (i for i in range(5))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
运行结果:
0 1 2 3 4
g = (i for i in range(5))
for el in g:
print(el)
运行结果:
0 1 2 3 4
list()
、tuple()
、set()
取值g = (i for i in range(5))
print(list(g))
print(tuple(g))
print(set(g))
运行结果:
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
{0, 1, 2, 3, 4}
真正理解生成器的惰性机制,来看一道例题:
def add(a, b):
return a + b
def test():
for r_i in range(4):
yield r_i
g = test()
for n in [2, 10]:
g = (add(n, i) for i in g)
print(list(g))
运行结果:
[20,21,22,23]
解析:生成器只有在取值的时候才会去运行,上述例题只有最后'print(list(g))'取值。
"""
g = test()
for n in [2, 10]:
g = (add(n, i) for i in g)
"""
所以上面的for循环可以写成如下代码:
"""
n = 10
g = (add(n, i) for i in (add(n, i) for i in test()))
"""
最终代入得到的列表为:[20, 21, 22, 23]
python中为了解决一些简单的需求可以使用一句话定义一个函数,这就是lambda匿名函数
lambda语法结构:
函数名 = lambda 形参:返回值
# def func(x, y):
# return x + y
# print(func(1, 2))
func = lambda x, y: x+y # 两个函数等价
print(func(1, 2))
运行结果:
3
注意事项:
func = lambda a,b,*args,sex= 'alex',c,**kwargs: kwargs
print(func(3, 4,c=666,name='zxd'))
# 只返回kwargs
运行结果:
{'name': 'zxd'}
func = lambda x:(x[0],x[2])
print(func('zxdnb'))
运行结果:
('z', 'd')
func = lambda x,y: x if x > y else y
print(func(3,100))
运行结果:
100
例一:
g = [lambda :i+1 for i in range(3)]
print([em() for em in g])
运行结果:
[3, 3, 3]
g = list()
for i in range(3):
def func():
return i + 1
g.append(func)
new_g = list()
for em in g:
new_g.append(em())
print(new_g)
运行结果:
[3, 3, 3]
例二:
g = [lambda i:i+1 for i in range(3)]
print([em(3) for em in g])
运行结果:
[4, 4, 4]
g = list()
for i in range(3):
def func(i):
return i + 1
g.append(func)
new_g = list()
for em in g:
new_g.append(em(3))
print(new_g)
运行结果:
[4, 4, 4]
例一:
g = (lambda i:i+1 for i in range(3))
print([em(3) for em in g])
运行结果:
[4, 4, 4]
def g():
for i in range(3):
def func(i):
return i + 1
yield func
new_g = list()
for em in g():
new_g.append(em(3))
print(new_g)
运行结果:
[4, 4, 4]
例二:
g = (lambda :i+1 for i in range(3))
print([em() for em in g])
运行结果:
[1, 2, 3]
def g():
for i in range(3):
def func():
return i + 1
yield func
new_g = list()
for em in g():
new_g.append(em())
print(new_g)
运行结果:
[1, 2, 3]
例三:
g = (lambda x:x*i for i in range(3))
for j in [2,10]:
g1 = (em(3) for em in g)
print([e+j for e in g1])
运行结果:
[10, 13, 16]
def g():
for i in range(3):
def func(x):
return x * i
yield func
for j in [2, 10]:
def g1():
for em in g():
yield em(3)
new_g = list()
for e in g1():
new_g.append(e + j)
print(new_g)
运行结果:
[10, 13, 16]
查看解释器内置常量和内置函数的方法
dir(__builtins__)
Python3.6.8的内置函数(共72个)
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 | |
property | quit | range | repr | reversed | round |
set | setattr | slice | sorted | staticmethod | str |
sum | super | tuple | type | vars | zip |
all() | any() | bytes() | callable() |
---|---|---|---|
chr() | ord() | complex() | divmid() |
eval() | exec() | frozenset() | help() |
globals() | locals() | hash() | id() |
iter() | next() | bin() | oct() |
int() | hex() | pow() | repr() |
round() | bool() |
all()
all(*args, **kwargs)
print(all([1, 2, 3, 4, 5]))
print(all([0, 1, 2, 3, 4]))
print(all([]))
运行结果:
True
False
True
any()
any(*args, **kwargs)
print(any([0, "", 1, False]))
print(any([0, "", [], False]))
print(any([]))
运行结果:
True
False
False
bytes()
bytes(value=b‘‘, encoding=None, errors=‘strict‘)
print("张旭东".encode("utf-8"))
print(bytes("张旭东", encoding="utf-8"))
运行结果:
b'\xe5\xbc\xa0\xe6\x97\xad\xe4\xb8\x9c'
b'\xe5\xbc\xa0\xe6\x97\xad\xe4\xb8\x9c'
callable()
callable(i_e_, some_kind_of_function)
__call__()
方法)def func():
print("hello world")
print(callable(func))
运行结果:
True
chr()
chr(*args, **kwargs)
print(chr(65))
运行结果:
A
ord()
ord(*args, **kwargs)
print(ord("A"))
运行结果:
65
complex()
complex(real, imag=None)
print(complex(20))
运行结果:
(20+0j)
divmid()
divmod(x, y)
(x // y, x % y)
print(divmod(10, 3))
运行结果:
(3, 1)
eval()(不推荐使用)
eval(*args, **kwargs)
print(eval("5 + 3"))
运行结果:
8
exec()(不推荐使用)
exec(*args, **kwargs)
exec("for i in range(10):print(i)")
运行结果:
0
1
2
3
4
frozenset()
frozenset(obj)
print(frozenset((1,2,3)))
运行结果:
frozenset({1, 2, 3})
help()
help(args)
help(list.append)
运行结果:
Help on method_descriptor:
append(...)
L.append(object) -> None -- append object to end
globals()
globals(*args, **kwargs)
a = 5
b = 10
def func():
print("hello world")
print(globals())
运行结果:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000221ED9D69E8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/python_S26/day12/exercise.py', '__cached__': None, 'a': 5, 'b': 10, 'func': <function func at 0x00000221ED8D1EA0>}
locals()
locals(*args, **kwargs)
a = 5
def func():
b = 10
print(locals())
func()
运行结果:
{'b': 10}
hash()
hash(*args, **kwargs)
print(hash("zxd"))
运行结果:
5236597812272808709
id()
id(*args, **kwargs)
print(id(10))
运行结果:
1864728976
iter()
iter(iterable, sentinel=None)
lst = [1, 2, 3, 4, 5]
t = iter(lst)
print(t)
运行结果:
<list_iterator object at 0x00000181FB2CA9B0>
next()
next(iterator, default=None)
t = iter([1, 2, 3, 4, 5])
print(next(t, None))
print(next(t, None))
print(next(t, None))
print(next(t, None))
print(next(t, None))
print(next(t, None))
运行结果:
1
2
3
4
5
None
bin()
bin(*args, **kwargs)
print(bin(10))
运行结果:
0b1010
oct()
oct(*args, **kwargs)
print(oct(10))
运行结果:
0o12
int()
int(x, base=10)
print(int("0b1010", 2))
print(int("0o12", 8))
运行结果:
10
10
hex()
hex(*args, **kwargs)
print(hex(20))
运行结果:
0x14
pow()
pow(*args, **kwargs)
print(pow(2, 4))
print(pow(2, 4, 3))
运行结果:
16
1
repr()
repr(obj)
s = "zxd"
print(repr(s))
运行结果:
'zxd'
round()
round(number, ndigits=None)
print(round(3.5))
运行结果:
4
abs() | format() | enumerate() | open() |
---|---|---|---|
range() | print() | input() | len() |
list() | dict() | str() | set() |
tuple() | float() | reversed | sum() |
dir() | type() | zip() | bool() |
abs()
abs(*args, **kwargs)
print(abs(-1))
运行结果:
1
format()
format(*args, **kwargs)
s = "你好"
print(format(s, ">20")) # 右对齐20位,多余的部分用空格补齐
print(format(s, "<20")) # 左对齐20位,多余的部分用空格补齐
print(format(s, "^20")) # 居中共20位,多余的部分用空格补齐
运行结果:
你好
你好
你好
s = 18
print(format(s, "08b")) # 共八位,转换为二进制
print(format(s, "08o")) # 共八位,转换为八进制
print(format(s, "08x")) # 共八位,转换为十六进制
print(format(s, "08d")) # 共八位,转换为十进制
运行结果:
00010010
00000022
00000012
00000018
enumerate()
enumerate(iterable, start=0)
lst = [1, 2, 3, 4, 5]
for i in enumerate(lst):
print(i)
运行结果:
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
lst = [1, 2, 3, 4, 5]
for i in enumerate(lst, 10): # 指定起始值
print(i)
运行结果:
(10, 1)
(11, 2)
(12, 3)
(13, 4)
(14, 5)
open()
open(file, mode=‘r‘, buffering=None, encoding=None, errors=None, newline=None, closefd=True)
file
、文件打开模式mode
、文件编码encoding
,返回一个文件句柄用于操作文件,其余参数暂时忽略f = open("text.txt", mode="r", encoding="utf-8")
f.read()
f.close()
range()
range(start, stop[, step])
for i in range(5):
print(i)
运行结果:
0
1
2
3
4
print()
print(self, *args, sep=‘ ‘, end=‘\n‘, file=None)
sep
来替代元素之间的逗号,可填入参数end
来控制结尾的换行,可填入参数file
将打印的内容写入文件print("zxd", "znb", sep="-", end="!")
运行结果:
zxd-znb!
input()
input(*args, **kwargs)
name = input("请输入姓名:")
print(name)
运行结果:
zxd
len()
len(*args, **kwargs)
lst = [1, 2, 3, 4, 5]
print(len(lst))
运行结果:
5
list()
list()
list(iterable)
print(list())
print(list(range(5)))
运行结果:
[]
[0, 1, 2, 3, 4]
dict()
dict()
dict(mapping)
dict(iterable)
dict(**kwargs)
print(dict())
print(dict({"k1": 1, "k2": 2}))
print(dict([("k1", 1), ("k2", 2)]))
print(dict(k1=1, k2=2))
运行结果:
{}
{'k1': 1, 'k2': 2}
{'k1': 1, 'k2': 2}
{'k1': 1, 'k2': 2}
str()
函数定义:
str()
str(value=‘‘, encoding=None, errors=‘strict‘)
函数说明:
默认创建空字符串
可将参数转换为字符串类型,若填入参数为字节类型,需指定编码方式
print(repr(str(123)))
print(str(b'\xe5\xbc\xa0\xe6\x97\xad\xe4\xb8\x9c',encoding="utf-8"))
运行结果:
张旭东
'123'
set()
set()
set(iterable)
print(set())
print(set([1,2,3,4,5]))
运行结果:
set()
{1, 2, 3, 4, 5}
tuple()
tuple()
tuple(iterable)
print(tuple())
print(tuple([1, 2, 3, 4, 5]))
运行结果:
()
(1, 2, 3, 4, 5)
float()
float(x)
print(float(123))
运行结果:
123.0
reversed
reversed(sequence)
lst = [1, 2, 3, 4, 5]
print(reversed(lst))
print(list(reversed(lst)))
运行结果:
<list_reverseiterator object at 0x000002043A55A9B0>
[5, 4, 3, 2, 1]
sum()
sum(*args, **kwargs)
print(sum([1, 2, 3, 4, 5]))
运行结果:
15
dir()
dir([object])
print(dir(list))
运行结果:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
type()
type(object_or_name, bases, dict)
type()
既是函数,又是元类(创造类的类),可以通过type()
创建一个类)print(type(list()))
运行结果:
<class 'list'>
zip()
zip(iter1 [,iter2 [...]])
lst1 = [1, 2, 3]
lst2 = [1, 2, 3, 4, 5]
print(zip(lst1, lst2))
print(list(zip(lst1, lst2)))
运行结果:
<zip object at 0x00000204D6E621C8>
[(1, 1), (2, 2), (3, 3)]
bool()
bool(x)
print(bool())
print(bool(123))
运行结果:
False
True
高阶函数全部需要结合规则函数,利用lambda匿名函数构造规则函数
filter() | 筛选过滤 |
---|---|
map() | 映射 |
sorted() | 排序 |
max() | 求最大值 |
min() | 求最小值 |
reduce() | 累计算 |
filter()
filter(function or None, iterable)
# 规则函数为None,返回可迭代对象中True的元素
print(list(filter(None, [0, 1, 2, 3])))
运行结果:
[1, 2, 3]
# 返回满足规则函数可迭代对象中的元素
print(list(filter(lambda x: x > 1, [0, 1, 2, 3])))
运行结果:
[2, 3]
map()
map(func, *iterables)
print(list(map(lambda x: x ** 2, [1, 2, 3])))
运行结果:
[1, 4, 9]
sorted()
sorted(*args, **kwargs)
key=规则函数
按照规则函数来排序,还可以指定reverse=True
来降序排列list.sort()
的区别:
list.sort()
改变的是原有列表sorted()
建立的新列表lst = [4, 2, 3, 7, 1]
print(sorted(lst))
print(lst) # 不改变原来列表
运行结果:
[1, 2, 3, 4, 7]
[4, 2, 3, 7, 1]
dic = {"k1": 3, "k2": 13, "k3": 1}
print(sorted(dic, key=lambda x: dic[x], reverse=True))
运行结果:
['k2', 'k1', 'k3']
max()
返回最大值
函数定义:
max(iterable, *[, default=obj, key=func])
max(arg1, arg2, *args, *[, key=func])
函数说明:
lst1 = [1, 2, 3, 4, 5, -6]
lst2 = []
print(max(lst1))
print(max(lst1, key=abs)) # 制定规则参数,返回绝对值最大的元素
print(max(lst2, default=1)) # 当lst2为空的时候返回1
运行结果:
5
-6
1
a = 5
b = 10
print(max(a, b))
运行结果:
10
min()
返回最小值
函数定义:
min(iterable, *[, default=obj, key=func])
min(arg1, arg2, *args, *[, key=func])
函数说明:
lst1 = [1, -2, 3, -4, 5, -6]
lst2 = []
print(min(lst1))
print(min(lst1, key=abs))
print(min(lst2, default=1))
运行结果:
-6
1
1
a = 5
b = 10
print(min(a, b))
运行结果:
5
reduce()
reduce(function, sequence, initial=None)
from functools import reduce
print(reduce(lambda x, y: x * y, [1, 2, 3, 4, 5]))
print(reduce(lambda x, y: x * y, [1, 2, 3, 4, 5], 5))
print(reduce(lambda x, y: x * y, [], 5))
运行结果:
120
600
5
classmethod() | delattr() | getattr() |
---|---|---|
hasattr() | issubclass() | isinstance() |
object() | property() | setattr() |
staticmethod() | super() |
原文:https://www.cnblogs.com/tianlangdada/p/11616318.html