- 论坛徽章:
- 0
|
最近正在加紧阅读2 editon.在第11章的时候,遇到这么一个操作:
#!/usr/bin/env python
from operator import add, sub,mul,div
from random import randint, choice
ops = {'+': add, '-': sub,'*': mul,'/':div}
MAXTRIES = 2
def doprob():
op = choice('+-*/')
nums = [ randint(1,10) for i in range(2) ]
nums.sort(reverse=True)
ans = ops[op](*nums) #就是这句,总觉得别扭。
pr = '%d %s %s = ' % (nums[0], op, nums[1])
oops = 0
while True:
try:
if int(raw_input(pr)) == ans:
print 'correct'
break
if oops == MAXTRIES:
print 'sorry... the answer is\n%s%d' % (pr, ans)
else:
print 'incorrect... try again'
oops += 1
except (KeyboardInterrupt,
EOFError, ValueError):
print 'invalid input... try again'
def main():
while True:
doprob()
try:
opt = raw_input('Again? [y] ').lower()
if opt and opt[0] == 'n':
break
except (KeyboardInterrupt, EOFError):
break
if __name__ == '__main__':
main()
ops是定义的全局字典,op是从四个运算符中随机得到的一个,(*nums)这就无从解释了,怎么就可以代表两个数字了呢?即使代表了两个数字,那怎么 ops[op] (*nums)就成了一个运算表达式了呢?还真的能返回正确的结果。如果我的运算是三个数字时,表达式如何写?
着实让我丈二的和尚-摸不着头脑。
python,dictory,还是我真的没能理解。还望哪位达人告知!
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/6303/showart_1086136.html |
|