为了账号安全,请及时绑定邮箱和手机立即绑定

使用 pprint 函数打印前五个元素

使用 pprint 函数打印前五个元素

慕工程0101907 2023-10-06 18:41:43
我正在尝试使用 pprint 函数打印前五个元素,但我无法让它工作。我已经尝试过以下代码,但它给了我一个错误。如何只打印前五个元素而不是前十个元素?wordCounts = pairs.reduceByKey(lambda x, y: x + y) wordCounts.pprint(:5)
查看完整描述

1 回答

?
www说

TA贡献1775条经验 获得超8个赞

由于问题没有提供简单的数据,我想该wordCounts变量是通过以下代码准备的。


import pprint

from pyspark.context import SparkContext

sc = SparkContext('local', 'test')

pairs = sc.parallelize([("a", 1), ("b", 1), ("b", 1), ("b", 1), ("b", 1), ("b", 1), ("d", 1), ("e", 1), ("a", 1), ("f", 1), ("c", 1)])

wordCounts = pairs.reduceByKey(lambda x, y: x + y)

您可以通过以下任一方式打印 wordCounts 中的值:


print(wordCounts.collect()[:5]) #Pick 5 elements

print(wordCounts.take(5)) #Pick 5 elements

print(sorted(wordCounts.collect())[:5]) #Sort the tuples, and pick the first 5 elements

print(sorted(wordCounts.collect(), key=lambda x: x[1], reverse=False)[:5]) #Sort by the second entry (i.e. count) in ascending order, and pick the first 5 elements

哪个产生


[('a', 2), ('b', 5), ('d', 1), ('e', 1), ('f', 1)]

[('a', 2), ('b', 5), ('d', 1), ('e', 1), ('f', 1)]

[('a', 2), ('b', 5), ('c', 1), ('d', 1), ('e', 1)]

[('d', 1), ('e', 1), ('f', 1), ('c', 1), ('a', 2)]

强烈建议您下次提供一个最小的可重现示例。


查看完整回答
反对 回复 2023-10-06
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信