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

a = {1,2,3}
b = {5,6,1}
print(a.intersection(b))
>>>
{1}
a = {1,2,3}
b = {5,6,1}
print(a.difference(b))
>>>
{2,3}
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}
上一篇下一篇

猜你喜欢

热点阅读