字典排序
>>> d={"user3":"a","user1":"b","user2":"c"}
>>> d.items()
dict_items([('user3', 'a'), ('user1', 'b'), ('user2', 'c')])
#按字典键升序排序
>>> sorted(d.items(),key=lambda x:x[0],reverse=False)
[('user1', 'b'), ('user2', 'c'), ('user3', 'a')]
#按字典键降序排序
>>> sorted(d.items(),key=lambda x:x[0],reverse=True)
[('user3', 'a'), ('user2', 'c'), ('user1', 'b')]
#按字典值升序排序
>>> sorted(d.items(),key=lambda x:x[1],reverse=False)
[('user3', 'a'), ('user1', 'b'), ('user2', 'c')]
#按字典值降序排序
>>> sorted(d.items(),key=lambda x:x[1],reverse=True)
[('user2', 'c'), ('user1', 'b'), ('user3', 'a')]
>>>
>>> sorted(d)
['user1', 'user2', 'user3']
>>> sorted(d.values())
['a', 'b', 'c']
>>> d
{'user3': 'a', 'user1': 'b', 'user2': 'c'}
>>>
>>> sorted(d.items(),key=lambda x:x[0],reverse=False)
[('user1', 'b'), ('user2', 'c'), ('user3', 'a')]
>>> keys_sort=sorted(d.items(),key=lambda x:x[0],reverse=False)
>>> keys_sort
[('user1', 'b'), ('user2', 'c'), ('user3', 'a')]
>>> d_new={}
>>> for tup in keys_sort:
... d_new[tup[0]]=tup[1]
...
>>> d_new
{'user1': 'b', 'user2': 'c', 'user3': 'a'}
>>> d
{'user3': 'a', 'user1': 'b', 'user2': 'c'}
字符串排序
>>> sorted([True,False])
[False, True]
s="9a13C85c7B24A6b" #正确的顺序应该为:abcABC135792468
#1.字母在前,数字在后
lis=sorted(s,key=lambda x:x.isdigit())
print("*")
print("".join(lis))
#1.字母在前,数字在后
#2.奇数在前,偶数在后
lis=sorted(s,key=lambda x:(x.isdigit(),x.isdigit() and int(x)%2==0))
print("**")
print("".join(lis))
#1.字母在前,数字在后
#2.奇数在前,偶数在后
#3.小写字母在前,大写字母在后
lis=sorted(s,key=lambda x:(x.isdigit(),x.isdigit() and int(x)%2==0,x.isalpha() and x.isupper()))
print("***")
print("".join(lis))
#1.字母在前,数字在后
#2.奇数在前,偶数在后
#3.小写字母在前,大写字母在后
#4.按照ascii码排序
lis=sorted(s,key=lambda x:(x.isdigit(),x.isdigit() and int(x)%2==0,x.isalpha() and x.isupper(),ord(x)))
print("****")
print("".join(lis))
面向对象编程
import math
class Point:
'Response a point in two-dimensional'
def __init__(self,x=0,y=0):
'''Initialize the position of a new point.'''
self.move(x,y)
def move(self,x,y):
'''Move the point to a new location'''
self.x=x
self.y=y
def reset(self):
'''Reset the point back to the geometric origin'''
self.move(0,0)
def calculate_distance(self,other):
'''Calculate the distance from this point to another point.'''
result=math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2)
return result
p1=Point()
p2=Point()
p1.reset()
p2.move(5,0)
print(p2.calculate_distance(p1))
print(p1.calculate_distance(p2))
assert p2.calculate_distance(p1) == p1.calculate_distance(p2)
p1.move(3,4)
print(p1.calculate_distance(p2))
print(p1.calculate_distance(p1))