溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Iterator and Generator-2

發(fā)布時間:2020-04-05 06:28:25 來源:網(wǎng)絡(luò) 閱讀:655 作者:cooperfang 欄目:編程語言

lambda表達(dá)式

匿名函數(shù)

# lambda  params:expression
# params : 可選參數(shù),逗號分割變量名
# expression:表達(dá)式,可以用條件語句,沒有return或yield

# 用法:
    # 簡單計算:lambda x: x*2
    # 添加條件: lambda x :True if x > 8 else False
    # 多個參數(shù) lambda x, y : x+y
    # 用作排序: users.sort(key = lambda x(x[0], x[1]))
    # 默認(rèn)字典:①defaultdic(lambda:0)
                # ② defaultdict(lambda:'bj')
                # ③ defaultdic(lambda :(0, 0))
    # 用作參數(shù):① filter ② map
    # 要點(diǎn):① 語法糖,用來創(chuàng)建函數(shù)對象  ② 表達(dá)式不要太復(fù)雜
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中有參數(shù)key,按照key的值進(jìn)行排序,以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]))  # 按數(shù)字大小排序
users
[('hmm', 15), ('coop', 23), ('lilei', 26), ('zhangsan', 40)]
from collections import defaultdict
d = defaultdict(lambda :0)  # 默認(rèn)賦值 等同于defaultdict(lambda:int)
只寫出key,而沒有指定value,默認(rèn)從int中取值,即0,而不限與0
d['a']
0
d
defaultdict(<function __main__.<lambda>()>, {'a': 0})
d['b']
0
d
defaultdict(<function __main__.<lambda>()>, {'a': 0, 'b': 0})
d['c'] = 'coop'
d
defaultdict(<function __main__.<lambda>()>, {'a': 0, 'b': 0, 'c': 'coop'})
city = defaultdict(lambda : 'bj')
city
defaultdict(<function __main__.<lambda>()>, {})
city['shanghai']
'bj'
city
defaultdict(<function __main__.<lambda>()>, {'shanghai': 'bj'})
city['coop']
'bj'
city
defaultdict(<function __main__.<lambda>()>, {'shanghai': 'bj', 'coop': 'bj'})
point = defaultdict(lambda : (0, 0))
point[1]
(0, 0)
point[0]
(0, 0)
point['pp'] = (1,2)
point
defaultdict(<function __main__.<lambda>()>,
            {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  # 對應(yīng)合并
# []列表  列表推到是
# ()生成器   生成器
# {k, v}    字典推倒
# set/{}    去重
# if 三元操作符   xx  if x else y
# enumerate   返回枚舉,帶索引
m = [1,2,3,0]
all(m)  # 可能是函數(shù)等
"""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 True
def f2():
    return False
def 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 sequence

Return 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)
<list_reverseiterator at 0x12fcd4c9d68>
for i in reversed(m):
    print(i)
5
4
3
2
1
[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 the
reverse 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 object

Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument.  The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration."""
x = [1,2,4,5,6,7,8]
y = ['q','b','c','d','e']
zip(x,y)
<zip at 0x12fcd3fc4c8>
print(zip(x,y))
<zip object at 0x0000012FCD4C6CC8>
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'}
# 列表推導(dǎo)式
[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]
# 生成器表達(dá)式()
(x**3 for i in range(8))
<generator object <genexpr> at 0x0000012FCD4B73B8>
for y in (x**3 for x in range(8)):
    print(y)
0
1
8
27
64
125
216
343
# 字典推導(dǎo)式
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'}
# 去重set
s = [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:
    pass
else:
    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
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI