Iterator and Generator-2
阿新 • • 發佈:2018-09-02
字典 function c4c can art signature number dict expr 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 # 按照字母順序排序
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) # 默認賦值
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 都是真
# any 任意
# 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 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‘}
# 列表推導式
[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))
<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
# 字典推導式
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
Iterator and Generator-2