class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
从简->难
list1 = [1,2,3] # --> [1,4,9]
# 循环
list2 = []
for _ in list1:
list2.append(_**2)
# 列表推导式
[i**2 for i in list1]
# map
list(map(lambda x:x**2,list1))
# 等价于
def f(x):
return x * x
list(map(f,list1))
下面都是一些简单的例子而已
list1 = [1,2,3]
list(map(str,list1))
students = [
{"name": "John Doe",
"father name": "Robert Doe",
"Address": "123 Hall street"
},
{
"name": "Rahul Garg",
"father name": "Kamal Garg",
"Address": "3-Upper-Street corner"
},
{
"name": "Angela Steven",
"father name": "Jabob steven",
"Address": "Unknown"
}
]
像例子1-2是烂大街的map举例的,像3这种就不太明显了,但却非常适合用map
list(map(lambda stu:stu['name'],students))
当然还有一个问题是这样的lambda你是否能想到?(虽然比较简单)
list1 = [1,2,3]
list2 = [4,5,6] # -> [4,10,18] 1*4 2*5 3*6
这个用列表推导式可以吗?反正我不太会做
[i*j for i in list1 for j in list2] # [4, 5, 6, 8, 10, 12, 12, 15, 18] # 可以看到是一个双重for循环
用map实现
list(map(lambda x,y:x*y,list1,list2)) # 你可以看到x来自list1,y来自list2
# ×2
def double(x):
return x + x
# 平方
def square(x):
return x * x
# 数据
list1 = [1, 2, 3 ]
# 处理
for i in list1:
temp = tuple(map(lambda x: x(i), (double, square)))
print(temp)
###
# (2, 1)
# (4, 4)
# (6, 9)
把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字
list1 = ['adam', 'LISA', 'barT']
list(map(lambda x:x.capitalize(),list1))
将一个数字字符串转换为整数的list
list(map(int,'1234'))
提取字典中的key
list(map(int,{1:2,2:3,3:4}))
快速生成26个英文字符
"".join(map(chr, range(ord('a'), ord('z') + 1)))
统计指定字符串每个字符出现的次数,从高到底排列
from collections import Counter
string = "AAABBCCAC"
print("".join(map(lambda x: x[0] + str(x[1]), Counter(string).most_common()))) #A4C3B2
在pandas中大量存在map等应用
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature
nums = [1,2,3,4,5]
list(filter(lambda x:x%2==1,nums))
names = ['alice','jordan','richardson','mike','hudson']
list(filter(lambda x:len(x)<=5,names))
list(filter(lambda num:int(str(num)[0])**3+int(str(num)[1])**3+int(str(num)[2])**3 == num,range(100,1000)))
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
reduce是相对来说比较难的一个函数,一方面是不常用,但在某些应用场景中用它就非常巧妙,另外一方面这个递推的过程你得理解。
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
此处的example对理解reduce非常重要
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
--->
((((1+2)+3)+4)+5)
有个递归的意思在里面from functools import reduce
from functools import reduce
reduce(lambda x,y:10*x+y, [1, 3, 5, 7, 9])
items = [12, 5, 7, 10, 8, 19]
list(map(lambda x: x ** 2, filter(lambda x: x % 2, items)))
# 其实用 列表推导式反而简单了
items = [12, 5, 7, 10, 8, 19]
[x ** 2 for x in items if x % 2]
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
string = '135'
print(str2int(string))
from functools import reduce
def prod(L):
return reduce(lambda x,y:x*y,L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
sorted是python的内置函数,可以排序容器,并且自己定义排序的策略
sorted(iterable, /, *, key=None, reverse=False)
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.
list1 = [1,3,5,2,4,6]
sorted(list1) # [1, 2, 3, 4, 5, 6]
sorted(list1,reverse=True) # [6, 5, 4, 3, 2, 1]
dict1 = {"zhangsan":18,"lisi":20,"wangwu":23,"hanmeimei":22}
sorted(dict1) # ['hanmeimei', 'lisi', 'wangwu', 'zhangsan']
list1 = [('A',3,200),('C',1,100),('B',2,300)]
sorted(list1,key=lambda x:x[1])
# [('C', 1, 100), ('B', 2, 300), ('A', 3, 200)]
sorted(list1,key=lambda x:x[0],reverse=False)
# [('A', 3, 200), ('B', 2, 300), ('C', 1, 100)]
sorted(list1,key=lambda x:x[2])
# [('C', 1, 100), ('A', 3, 200), ('B', 2, 300)]
urls=['http://c.biancheng.net',
'http://c.biancheng.net/python/',
'http://c.biancheng.net/shell/',
'http://c.biancheng.net/java/',
'http://c.biancheng.net/golang/']
sorted(urls,key=lambda x:len(x))
sorted("This is a test string from Andrew".split(), key=str.lower)
# ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __repr__(self):
return self.name
infos = [Person("wuxianfeng",18),Person("zhangsan",23),Person("lisi",21)]
sorted(infos,key=lambda per:per.age) # [wuxianfeng, lisi, zhangsan]
PyWebIO 提供了一系列命令式的交互函数,能够让咱们用只用 Python 就可以编写 Web 应用, 不需要编写前端页面和后端接口, 让简易的 UI 开发效率大大提高