sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
list.sort() 在列表上修改,无返回值
sorted() 函数中取 关键词 key
sorted(iterable=可迭代的对象, key=可迭代对象中 的元素, reverse=(True/False是否反转))
sorted() 运用在 list 上, 对字典 需要先将其转换为 列表嵌套"字典"的结构 , 可以用 dict.items() 或者 zip(dic.keys(),dic.values())
>>> dic= {'name':'Akito','age':25, 'city':"tokyo"}
>>> list1=zip(dic.keys(),dic.values()) # 方法1,将dict转化成list
>>> list2=dic.items() # 方法2,将dict转化成list
>>> print (list(list1))
[('name', 'Akito'), ('age', 25), ('city', 'tokyo')]
>>> print (list(list2))
[('name', 'Akito'), ('age', 25), ('city', 'tokyo')]
>>>
>>> res1=sorted(list2,key=lambda x:x[0], reverse=True) # 列表嵌套,使用list每个元素的首位元素字母大小 排序
>>> print (res1)
[('name', 'Akito'), ('city', 'tokyo'), ('age', 25)]
>>> res1= [('name', 'Akito'), ('city', 'tokyo'), ('age', '25'), ('provience', 'tokyo')]
>>> res2=sorted(res1, key=lambda x:(x[1],x[0])) # 当列表key值相同时,添加额外判断元素,此处为先x[1],再x[0]
>>> print (res2)
[('age', '25'), ('name', 'Akito'), ('city', 'tokyo'), ('provience', 'tokyo')]
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
程序分析:创建一个新的 3 行 3 列的矩阵,使用 for 迭代并取出 X 和 Y 矩阵中对应位置的值,相加后放到新矩阵的对应位置中。
>>> [map(lambda a,b: a+b, X[i],Y[i]) for i in range(3)]
>>> [[17, 15, 4], [10, 12, 9], [11, 13, 18]]
MAXIMUM = lambda x,y : (x > y) * x + (x < y) * y
MINIMUM = lambda x,y : (x > y) * y + (x < y) * x
boolen 为 0 或 1
x , y 相比较, 并 乘以 x, y 的值,获得 Max 和 Min
>>> a = [1,2,3,4]
>>> [ x for x in (map(lambda x: x*x*x, a)) if x > 10]
[27, 64]
map ( 函数, 列表)
- 即列表中的每个元素做函数运算
[x for x in 列表/Str]
- 即返回每个列表或元素
if x > 10
- 即对每次循环做Boolean验证
# code ver python3
from math import ceil
def chunk(lst, size):
return list(map(lambda x: lst[x*size:x*size+size],list(range(0,ceil(len(lst)/size)))))
# == lambda( x: lst[x*size:x*size+size], [0,1,2])
# ceil #math.ceil() function returns the smallest integral value greater than the number.除法后的最小整数
>>> print (chunk([1,3,5,7,9,11,13],3))
[[1, 3, 5], [7, 9, 11], [13]]
import re
def count_vowels(str):
return len(re.findall(("a|o"), str, re.IGNORECASE))
print (count_vowels( "foobar" )) # 3
print (count_vowels( "gym" )) # 0
>>>3
>>>0
class JD():
def __init__(self, title, salary, bouns):
self.Title = title
self.TC = salary+"+"+bouns
def candidate(self, candi_name):
print ("Candidate %s has been offered %s Position with TC as %s"%(candi_name,self.Title,self.TC))
#>>> IT-1911=JD("techlead","100k", "10%")
#>>> IT-1911.candidate("WU")
#Candidate WU has been offered techlead Position with TC as 100k+10%