2017-08-15 59 views
-1

我有以下Pyspark劈裂列表內的列表,元組

[('HOMICIDE', [('2017', 1)]), 
('DECEPTIVE PRACTICE', [('2017', 14), ('2016', 14), ('2015', 10), ('2013', 4), ('2014', 3)]), 
('ROBBERY', [('2017', 1)])] 

如何,當我試圖使用映射其作爲「AttributeError的投擲轉換爲

[('HOMICIDE', ('2017', 1)), 
('DECEPTIVE PRACTICE', ('2015', 10)), 
('DECEPTIVE PRACTICE', ('2014', 3)), 
('DECEPTIVE PRACTICE', ('2017', 14)), 
('DECEPTIVE PRACTICE', ('2016', 14))] 

:‘名單’對象沒有屬性'map'「

rdd = sc.parallelize([('HOMICIDE', [('2017', 1)]), ('DECEPTIVE PRACTICE', [('2017', 14), ('2016', 14), ('2015', 10), ('2013', 4), ('2014', 3)])]) 
y = rdd.map(lambda x : (x[0],tuple(x[1]))) 

回答

2

maprdd而不是蟒蛇列表的方法,所以你需要先並行列表,然後你可以使用flatMap拉平內列出:

rdd = sc.parallelize([('HOMICIDE', [('2017', 1)]), 
         ('DECEPTIVE PRACTICE', [('2017', 14), ('2016', 14), ('2015', 10), ('2013', 4), ('2014', 3)]), 
         ('ROBBERY', [('2017', 1)])]) 

rdd.flatMap(lambda x: [(x[0], y) for y in x[1]]).collect() 

# [('HOMICIDE', ('2017', 1)), 
# ('DECEPTIVE PRACTICE', ('2017', 14)), 
# ('DECEPTIVE PRACTICE', ('2016', 14)), 
# ('DECEPTIVE PRACTICE', ('2015', 10)), 
# ('DECEPTIVE PRACTICE', ('2013', 4)), 
# ('DECEPTIVE PRACTICE', ('2014', 3)), 
# ('ROBBERY', ('2017', 1))] 
+0

得到它的工作...感謝您的信息... –

2

而不是列表理解呢?

y = [(x[0], i) for x in rdd for i in x[1]] 

返回

[('HOMICIDE', ('2017', 1)), ('DECEPTIVE PRACTICE', ('2017', 14)), ('DECEPTIVE PRACTICE', ('2016', 14)), ('DECEPTIVE PRACTICE', ('2015', 10)), ('DECEPTIVE PRACTICE', ('2013', 4)), ('DECEPTIVE PRACTICE', ('2014', 3))] 
+0

它在python中運行良好,當我使用pyspark時,我必須將數據移動到磁盤....我認爲它的我的壞不要提及sc.parallelize在我的 題 。謝謝@ason​​gtoruin –

+0

@SachinSukumaran我的不好!無論如何,另一個答案似乎有你覆蓋。 – asongtoruin