成语“减少”包含另一个方法列表的列表
我遇到了一种情况,我想通过另一个方法列表“减少”一个整数列表。
>>> import operator
>>>
>>> OPS = [operator.add, operator.sub, operator.add]
>>> nums = [1,2,3,4]
>>>
>>> OPS[2](OPS[1](OPS[0](nums[0],nums[1]),nums[2]),nums[3])
4
for循环:
>>> result = nums[0]
>>> for i in range(1,len(nums)):
... result = OPS[i-1](result,nums[i])
...
>>> print result
4
“queues”:
>>> result = nums.pop(0)
>>> while nums:
... result = OPS.pop(0)(result, nums.pop(0))
...
>>> print result
4
如果我只想对数字列表应用一种方法,例如operator.add,我可以使用reduce。
>>> reduce(operator.add, [1,2,3,4])
10
是否有类似的方法可以组合两个列表,一个是运算符,另一个是操作数?
I came across a situation where I wanted to "reduce" one list of integers by another list of methods.
>>> import operator
>>>
>>> OPS = [operator.add, operator.sub, operator.add]
>>> nums = [1,2,3,4]
>>>
>>> OPS[2](OPS[1](OPS[0](nums[0],nums[1]),nums[2]),nums[3])
4
for loop:
>>> result = nums[0]
>>> for i in range(1,len(nums)):
... result = OPS[i-1](result,nums[i])
...
>>> print result
4
"queues":
>>> result = nums.pop(0)
>>> while nums:
... result = OPS.pop(0)(result, nums.pop(0))
...
>>> print result
4
If I just wanted to apply one method to the list of numbers, for example operator.add, I could use reduce.
>>> reduce(operator.add, [1,2,3,4])
10
Is there something similar for combining two lists, one of operators and another of operands?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有。
Nope.
与 Ignacio 的解决方案类似,但具有迭代器和 izip,并且仅适用于 Python << 3.x:
Similar to Ignacio's solution, but with iterators and izip, and only for Python < 3.x: