代码:
from functools import reduce
num = 2989
numSplit = [int(x) for x in str(num)]
# convert the number to a list with each digit separated
numProduct = reduce((lambda x,y: x*y), numSplit)
# uses reduce to multiply each number in order
print(numProduct)
问题:
使用NumProduct,我试图找到2*9
,9*8
和8*9
的单独产品。
我不确定如何修改lambda以仅查找[2,9,8,9]
中的数字对(或其他各种长度)的乘积。需要协助。 Tnx。
答案 0 :(得分:3)
Reduce()
会将整个可迭代项减少为一个值-这不是您想要的。相反,可以考虑将相邻的值分组,然后在每个组中采用乘积。
num = 2989
numSplit = [int(x) for x in str(num)]
numProduct = [x * y for x, y in zip(numSplit, numSplit[1:])]
我在这里zip
numSplit
的列表中,numSplit
的一个切片偏移了一个,以将每个数字与其右边的邻居分组。然后,我对此进行迭代,将两个值相乘。如果一个列表比另一个列表短,则zip
会将所有列表都截短为最短的长度-这就是这里发生的情况,从而防止在末尾出现多余的项。
结果:
>>> numProduct
[18, 72, 72]
更新
如果要支持任意大小的分组,请使用以下内容:
from functools import reduce
from operator import mul
num = 2989
size = 3
numSplit = [int(x) for x in str(num)]
numProduct = [reduce(mul, p) for p in zip(*(numSplit[x:] for x in range(size)))]
结果:
>>> numProduct
[144, 648]
答案 1 :(得分:0)
如果您确实想要,可以在此处使用reduce。
if object_id('ForSubQuery') is not null begin
DROP TABLE ForSubQuery
end
Create Table ForSubQuery
(
SecID int
)
INSERT INTO ForSubQuery SELECT 123
INSERT INTO ForSubQuery SELECT 234
GO
SELECT * FROM ForSubQuery
if object_id('MainTable') is not null begin
DROP TABLE MainTable
end
Create Table MainTable
(
IsPrior bit,
IsCurrent bit,
IsIdeal bit,
[SecurityID] int,
PosID int
)
INSERT INTO MainTable SELECT 1,1,1,123,1
INSERT INTO MainTable SELECT 0,1,1,234,2
INSERT INTO MainTable SELECT 1,0,0,234,3
GO
SELECT * FROM MainTable
SELECT
CASE
WHEN
Position.IsPrior = 1
AND Position.[SecurityID] in (SELECT
SecID
FROM ForSubQuery
)
THEN 1
ELSE 0
END AS IsPriorAfter
,CASE
WHEN
Position.IsIdeal = 1
AND [Position].[SecurityID] IN (SELECT
secid
FROM ForSubQuery
)
THEN 1
ELSE 0
END AS IsIdealAfter
,CASE
WHEN
Position.IsCurrent = 1
AND [Position].[SecurityID] IN (SELECT
secid
FROM ForSubQuery
)
THEN 1
ELSE 0
END AS IsCurrentAfter
, Position.*
FROM MainTable [Position]
order by Position.PosID