filter,map并且reduce在Python 2中完美地工作.这是一个例子:
>>> def f(x):
return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x):
return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x,y):
return x+y
>>> reduce(add, range(1, 11))
55
Run Code Online (Sandbox Code Playgroud)
但是在Python 3中,我收到以下输出:
>>> filter(f, range(2, 25))
<filter object at 0x0000000002C14908>
>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70> …Run Code Online (Sandbox Code Playgroud) 我需要编写一个函数,它接受一个数字列表并将它们相乘.例子:
[1,2,3,4,5,6]会给我1*2*3*4*5*6.我真的可以使用你的帮助.
是否可以使用列表理解来模拟sum()之类的东西?
例如 - 我需要计算列表中所有元素的乘积:
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
Run Code Online (Sandbox Code Playgroud)
执行相同的代码:
def product_of(input):
result = 1
for i in input:
result *= i
return result
Run Code Online (Sandbox Code Playgroud) 我正在研究Project Euler 问题12,因此我需要针对超过500个独特因子的倍数进行一些测试.
我认为数组[1,2,3 ... 500]将是一个很好的起点,因为该数组的乘积是可能的最低数字.但是,numpy.prod()为此数组返回零.我确定我错过了一些明显的东西,但到底是什么?
>>> import numpy as np
>>> array = []
>>> for i in range(1,100):
... array.append(i)
...
>>> np.prod(array)
0
>>> array.append(501)
>>> np.prod(array)
0
>>> array.append(5320934)
>>> np.prod(array)
0
Run Code Online (Sandbox Code Playgroud) 我正试图在hackerrank比赛中找到一个有趣的问题,并且出现了这个问题.我使用itertools,这是代码:
import itertools
l = []
for _ in range(int(input())):
l.append(int(input()))
max = l[0] * l[len(l)-1]
for a,b in itertools.combinations(l,2):
if max < (a*b):
max = (a*b)
print(max)
Run Code Online (Sandbox Code Playgroud)
他们还有其他任何有效的方法吗?因为我在一些我无法访问的测试用例中得到时间错误(因为它是一个小小的竞赛).
可能重复:
返回列表的产品
有没有其他方法来获得列表的产品,而不是这样:
def prod(L):
p=1
for i in L:
p= i * p
return p
Run Code Online (Sandbox Code Playgroud)
这段代码是正确的,但我需要找到另一种方法来做到这一点.我真的找不到它.
是否有一个python等效的MATLAB命令"prod"(这里描述)?
如何将此列表与python相乘:
A = [ [0.45, 0.89, 0.91],
[0.5, 0.78, 0.55],
[0.134, 0.571, 0.142] ]
Run Code Online (Sandbox Code Playgroud)
如何乘以每列,例如0.45*0.5*0.134 = 0.03015; 0.89*0.78*0.571 = 0.3961; 0,91*0.55*0.142 = 0.071071
[0.03015,0.3961,0.071071]
Run Code Online (Sandbox Code Playgroud)
我怎么能用python做到这一点?
我有以下列表:
list1 = [1, 5, 7, 13, 29, 35, 65, 91, 145, 203, 377, 455, 1015, 1885, 2639, 13195]
Run Code Online (Sandbox Code Playgroud)
如何将列表中的每个数字相乘?例如1 * 5 * 7 * 13 * 29..etc.
我是否正确使用下面的代码?:
for numbs in list1:
numbs * list1[#iterate through list1, starting on 2nd item in list1]
Run Code Online (Sandbox Code Playgroud)