是问题的背景背景:
....
ops = {'+':add,'-':sub}
op = choice('+-')
nums = [randint(1,10) for i in range(2)]
....
ans = ops[op](*nums)
有人可以帮助我吗?
答案 0 :(得分:0)
您可以使用接受函数和迭代的reduce
,并将该函数累积应用于迭代。
>>> from operator import add, sub
>>> from random import choice, randint
>>> ops = {'+':add, '-':sub}
>>> op = choice('+-')
>>> op
'+'
>>> nums = [randint(1,10) for i in range(10)]
>>> nums
[7, 8, 1, 4, 10, 7, 10, 7, 10, 1]
>>> reduce(ops[op], nums)
65
reduce(add, [1, 2, 3])
=> add(add(1, 2), 3)
如果您想在Python 3.x中使用reduce
,请从functools
导入:
from functools import reduce