python中字典长度可变吗_字典运算的一个疑惑---已解决(可变长度的参数)[zt]

字典运算的一个疑惑---已解决(可变长度的参数)[zt]

字典运算的一个疑惑---已解决(可变长度的参数)

http://blog.chinaunix.net/u/6303/showart_1086136.html 最近正在加紧阅读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,还是我真的没能理解。还望哪位达人告知!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

python容许程序员执行一个没有显式定义参数的函数,相应的方法就是通过一个元组(非关键字参数)或字典(关键字参数)作为参数组传递给参数。基本上,可以将所有参数放进一个元组或字典中,仅仅用这些装有参数的容器来调用一个函数,而不必显式地把它们放在函数调用中:

func(*tuple_grp_nonkw_args,**dict_grp_kw_args)

完整的带有形参的语法为:

func(positional_args,keyword_args,*tuple_grp_nonkw_args,**dict_grp_kw_args)

有了上面的解释,我们就可以准确的理解程序中出现的 ans = ops[op](*nums)

nums是经过排序的两个数字,ops是一个字典,[op]是返回一个预定义过的+-*/符号中的一个,那么ops[op]联合使用就是找出字典中label所对应的vaule.

这条语句经过翻译解释后,应是这样的: ans = nums[0] add/sub/mul/div nums[1].

这样理解了之后,我们验证一下,那就是我们将随机数增加到3个,显然这条语句已经不能满足需求,我们把它这种隐式的写法更改为:

(注:其实我们仍然可以*nums元组来表示参数,但是局限在于opt[op]不接受不是2个的参数,所以退而求其次,放弃这种可变长度参数的隐式写法)

#!/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(3) ]

nums.sort(reverse=True)

ans = ops[op](nums[0],nums[1])

ans1 = ops[op](ans,nums[2])

pr = '%d %s %s %s %d = ' % (nums[0], op, nums[1],op,nums[2])

oops = 0

while True:

try:

if int(raw_input(pr)) == ans1:

print 'correct'

break

if oops == MAXTRIES:

print 'sorry... the answer is\n%s%d' % (pr, ans1)

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()

验证通过!

让我们进入交互式python,再测试一次,可变长度参数之非关键字元组篇

>>> def tupleVarArgs (arg1,arg2='default',*theRest):

...     print 'formal arg 1', arg1

...     print 'formar arg2:', arg2

...     for eachXtrArg in theRest:

...         print 'another arg:',eachXtrArg

...

>>> tupleVarArgs('abc')

formal arg 1 abc

formar arg2: default

>>> tupleVarArgs(34,5.3)

formal arg 1 34

formar arg2: 5.3

>>> tupleVarArgs(34,5.3,'xxxx','yyyy','zzzz')

formal arg 1 34

formar arg2: 5.3

another arg: xxxx

another arg: yyyy

another arg: zzzz

*号的威力,也可见一斑。。。

©著作权归作者所有:来自51CTO博客作者3444542的原创作品,如需转载,请注明出处,否则将追究法律责任

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值