例子1[(2,3),(1,4),(5,1),(1,6)]用元组中的最大值进行排序
number_list = [(2,3),(1,4),(5,1),(1,6)]
#方法一:
print sorted(number_list,key = lambda x: max(x))
#方法二:
print sorted(number_list,key = lambda x: x[0]>x[1] and x[0] or x[1])
#方法三:
#说明True*4=4,False*4=0
print sorted(number_list,key = lambda x: (x[0]>x[1])*x[0] + (x[0]<x[1])*x[1])
不支持优先级的计算器
#!/usr/bin/env python
#将数字和字符串拆分成2个列表
def op_str(input_str):
op_list = []
num_str = ''
for i in input_str:
if i == '+' or i == '-' or i == '*' or i == '/':
op_list.append(i)
num_str = num_str + ' '
else:
num_str = num_str + i
tmp_list = [op_list,num_str]
return tmp_list
#根据相应的算法,做相应的操作
def op(actions):
op_action = actions[0]
tmp_str = actions[1]
num_list = tmp_str.split()
for i in op_action:
if i == '+':
tmp_sum = int(num_list[0]) + int(num_list[1])
num_list[:2] = [tmp_sum]
elif i == '-':
tmp_sum = int(num_list[0]) - int(num_list[1])
num_list[:2] = [tmp_sum]
elif i == '*':
tmp_sum = int(num_list[0]) * int(num_list[1])
num_list[:2] = [tmp_sum]
elif i == '/':
if num_list[1] == '0':
print 'Error'
else:
tmp_sum = (int(num_list[0]) + 0.0) / int(num_list[1])
num_list[:2] = [tmp_sum]
return num_list
#让用户输入一个表达式,支持负数开头的
expression = raw_input('Please input the expression: ')
#判断表达式是否以'-'开头,如果以'-'开头,就去掉'-'
if (expression.strip()).startswith('-'):
str = (expression.strip()).replace('-','',1)
tmp_list = op_str(str)
tmp_list[1] = '-' + tmp_list[1]
#print tmp_list
result = op(tmp_list)
print result[0]
else:
tmp_list = op_str(expression.strip())
result = op(tmp_list)
print result[0]
转载于:https://blog.51cto.com/ly36843/1718087