我有一個并行化的元組串列,格式如下:
data= [('Emily', (4, 2)),
('Alfred', (1, 12)),
('George', (10, 2))]
list = sc.parallelize(data)
我想要的是將元組中的整數相乘,這會給我這個輸出:
[('Emily', (8)),
('Alfred', (12)),
('George', (20))]
我努力了:
list = list.map(lambda x: (x[0], x[1]*x[2]))
但沒有效果。
uj5u.com熱心網友回復:
在您中,lambdax[1]是一個元組 ( (4, 2)...),因此您需要訪問要相乘的第一個和第二個值 ( x[1][0]...)。
試試這個:
result = list.map(lambda x: (x[0], x[1][0] * x[1][1]))
print(result.collect())
#[('Emily', 8), ('Alfred', 12), ('George', 20)]
另一種方法是將元組傳遞給帶有mul運算子的reduce 函式:
import operator
import functools
list.map(lambda x: (x[0], functools.reduce(operator.mul, x[1], 1)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383923.html
