Iterator and Generator-2
发表于:2024-11-25 作者:热门IT资讯网编辑
编辑最后更新 2024年11月25日,lambda表达式匿名函数# lambda params:expression# params : 可选参数,逗号分割变量名# expression:表达式,可以用条件语句,没有return或yie
lambda表达式
匿名函数
# lambda params:expression# params : 可选参数,逗号分割变量名# expression:表达式,可以用条件语句,没有return或yield# 用法: # 简单计算:lambda x: x*2 # 添加条件: lambda x :True if x > 8 else False # 多个参数 lambda x, y : x+y # 用作排序: users.sort(key = lambda x(x[0], x[1])) # 默认字典:①defaultdic(lambda:0) # ② defaultdict(lambda:'bj') # ③ defaultdic(lambda :(0, 0)) # 用作参数:① filter ② map # 要点:① 语法糖,用来创建函数对象 ② 表达式不要太复杂
f = lambda x :x*2
f(3)
6
f = lambda x : True if x > 8 else False # 在if前面的是要返回的值
f(3)
False
f(9)
True
f = lambda x, y : x + y
f(8,9)
17
users = [('coop', 23), ('lilei', 26), ('hmm', 15), ('zhangsan', 40)]
users.sort(key=lambda x: (x[0],x[1])) # sort中有参数key,按照key的值进行排序,以x[0]# 的值为key # 按照字母顺序排序x[0]指出了是coop,lilei,hmm等
users
[('coop', 23), ('hmm', 15), ('lilei', 26), ('zhangsan', 40)]
users.sort(key=lambda x:(x[1],x[0])) # 按数字大小排序
users
[('hmm', 15), ('coop', 23), ('lilei', 26), ('zhangsan', 40)]
from collections import defaultdict
d = defaultdict(lambda :0) # 默认赋值 等同于defaultdict(lambda:int)只写出key,而没有指定value,默认从int中取值,即0,而不限与0
d['a']
0
d
defaultdict(()>, {'a': 0})
d['b']
0
d
defaultdict(()>, {'a': 0, 'b': 0})
d['c'] = 'coop'
d
defaultdict(()>, {'a': 0, 'b': 0, 'c': 'coop'})
city = defaultdict(lambda : 'bj')
city
defaultdict(()>, {})
city['shanghai']
'bj'
city
defaultdict(()>, {'shanghai': 'bj'})
city['coop']
'bj'
city
defaultdict(()>, {'shanghai': 'bj', 'coop': 'bj'})
point = defaultdict(lambda : (0, 0))
point[1]
(0, 0)
point[0]
(0, 0)
point['pp'] = (1,2)
point
defaultdict(()>, {1: (0, 0), 0: (0, 0), 'pp': (1, 2)})
有些代码----一行搞定
# all(iterable) Return True if all elements of the iterable are true (or if the iterable is empty). 都是真 # any(iterable)Return True if any element of the iterable is true. If the iterable is empty, return False 任意# min# max# sum# reversed# sorted# zip # 对应合并# []列表 列表推到是# ()生成器 生成器# {k, v} 字典推倒# set/{} 去重# if 三元操作符 xx if x else y# enumerate 返回枚举,带索引
m = [1,2,3,0]
all(m) # 可能是函数等"""Signature: all(iterable, /)Docstring:Return True if bool(x) is True for all values x in the iterable括号里面必须是可迭代的对象,如果可迭代对象里面的每一个都是True,则返回True"""
False
m = [1,2,3,4,5]all(m)
True
def f1(): return Truedef f2(): return Falsedef f3(): return True
all([f1(), f2(), f3()]) # [],可迭代的对象
False
# any
any([f1(), f2(), f3()])
True
m
[1, 2, 3, 4, 5]
min(m)
1
max(m)
5
sum(m)"""Signature: sum(iterable, start=0, /)Docstring:Return the sum of a 'start' value (default: 0) plus an iterable of numbers"""
"Signature: sum(iterable, start=0, /)\nDocstring:\nReturn the sum of a 'start' value (default: 0) plus an iterable of numbers\n"
sum(m)
15
reversed(m)"""Init signature: reversed(self, /, *args, **kwargs)Docstring: reversed(sequence) -> reverse iterator over values of the sequenceReturn a reverse iterator"""
'Init signature: reversed(self, /, *args, **kwargs)\nDocstring: \nreversed(sequence) -> reverse iterator over values of the sequence\n\nReturn a reverse iterator'
reversed(m)
for i in reversed(m): print(i)
54321
[i for i in reversed(m)]
[5, 4, 3, 2, 1]
[i for i in reversed(range(8))]
[7, 6, 5, 4, 3, 2, 1, 0]
m
[1, 2, 3, 4, 5]
m = [2,3,90,5,4,34,22,55]m.sort()
m
[2, 3, 4, 5, 22, 34, 55, 90]
m = [2,3,90,5,4,34,22,55]
sorted(m)
[2, 3, 4, 5, 22, 34, 55, 90]
sorted?"""Signature: sorted(iterable, /, *, key=None, reverse=False)Docstring: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 thereverse flag can be set to request the result in descending order.Type: builtin_function_or_method"""
m
[2, 3, 90, 5, 4, 34, 22, 55]
sorted(m, reverse=False)
[2, 3, 4, 5, 22, 34, 55, 90]
sorted(m, reverse=True)
[90, 55, 34, 22, 5, 4, 3, 2]
m1 = [-9,-3,-5,-7,3,4,6]
sorted(m1)
[-9, -7, -5, -3, 3, 4, 6]
sorted(m1, key = abs)
[-3, 3, 4, -5, 6, -7, -9]
zip?"""Init signature: zip(self, /, *args, **kwargs)Docstring: zip(iter1 [,iter2 [...]]) --> zip objectReturn a zip object whose .__next__() method returns a tuple wherethe i-th element comes from the i-th iterable argument. The .__next__()method continues until the shortest iterable in the argument sequenceis exhausted and then it raises StopIteration."""
x = [1,2,4,5,6,7,8]
y = ['q','b','c','d','e']
zip(x,y)
print(zip(x,y))
print(list(zip(x,y)))
[(1, 'q'), (2, 'b'), (4, 'c'), (5, 'd'), (6, 'e')]
print(dict(zip(x,y)))
{1: 'q', 2: 'b', 4: 'c', 5: 'd', 6: 'e'}
name = ['coop','hmm','lilei']city = ['beijing','shanghai','shenzhen']
dict(zip(name,city))
{'coop': 'beijing', 'hmm': 'shanghai', 'lilei': 'shenzhen'}
# 列表推导式[i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[i^2 for i in range(10)]
[2, 3, 0, 1, 6, 7, 4, 5, 10, 11]
# 生成器表达式()(x**3 for i in range(8))
at 0x0000012FCD4B73B8>
for y in (x**3 for x in range(8)): print(y)
0182764125216343
# 字典推导式info = dict(zip(name, city))
info
{'coop': 'beijing', 'hmm': 'shanghai', 'lilei': 'shenzhen'}
info_new = {}for k, v in info.items(): info_new[k] = v.upper()print(info_new)
{'coop': 'BEIJING', 'hmm': 'SHANGHAI', 'lilei': 'SHENZHEN'}
{k:v.upper() for k, v in info.items()} # 与上面同样的效果
{'coop': 'BEIJING', 'hmm': 'SHANGHAI', 'lilei': 'SHENZHEN'}
# 去重sets = [1,1,2,3,4,5,4,5,64,6,4,3,6]
set(s)
{1, 2, 3, 4, 5, 6, 64}
s
[1, 1, 2, 3, 4, 5, 4, 5, 64, 6, 4, 3, 6]
list(set(s))
[64, 1, 2, 3, 4, 5, 6]
三元操作符
if True: passelse: pass
True if s =='a' else False
False
s
[1, 1, 2, 3, 4, 5, 4, 5, 64, 6, 4, 3, 6]
s = 'a'
True if s =='a' else False
True