yield&map&set
2023-01-24 本文已影响0人
山猪打不过家猪
1.yield
使用next
来调用yield
def mygenerator(n):
for x in range(n):
yield x*3
values = mygenerator(100000)
print(next(values))
print(next(values))
print(next(values))
print(next(values))
2.map
map(func,data)
>>> def double(x):
... return x * 2
...
>>> map(double, [1, 2, 3, 4])
<map object at 0x...>
>>> list(map(double, [1, 2, 3, 4]))
[2, 4, 6, 8]
>>> list(map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]))
[5, 7, 9]
3.set
- 两个set的交集
a = {1,2,3}
b = {5,6,1}
print(a.intersection(b))
>>>
{1}
- set a里面有的,b里无的
a = {1,2,3}
b = {5,6,1}
print(a.difference(b))
>>>
{2,3}
- 去掉两个set相同的后剩下的
a = {1,2,3}
b = {5,6,1}
print(a.symmetric_difference(b))
>>>
{2, 3, 5, 6}
- 并集
a = {1,2,3}
b = {5,6,1}
print(a.union(b))
>>>
{1, 2, 3, 5, 6}