python - 使用 pprint 函数打印前五个元素
问题描述
我正在尝试使用 pprint 函数打印前五个元素,但我无法让它工作。我尝试了以下代码,但它给了我一个错误。如何只打印前五个元素而不是前十个元素?
wordCounts = pairs.reduceByKey(lambda x, y: x + y)
wordCounts.pprint(:5)
解决方案
由于问题没有提供简单的数据,我想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)]
强烈建议您下次提供一个可重现的最小示例。
推荐阅读
- python - 什么是 BinOps?
- javascript - 循环中等待解决之前的javascript返回
- excel - VBA - 1004:应用程序定义或对象定义的错误仅在导出到包含大量数据的 Excel 时出现
- javascript - 为什么 React 官方文档将 useEffect 与 componentDidMount 和 componentDidUpdate 进行比较?
- javascript - JS Array value 渲染 undefined,所以出现 Uncaught type Error
- mysql - mySQL 修复新数据库完整性实现外键
- kubespray - 如何升级 kubespray kubernetes 集群容器运行时?
- python - 使用 Pandas,如何删除具有 2 级多索引标题的数据框中的空列
- unix - 检查主目录 UNIX 的字段值
- date - Octobercms twig 如何显示即将到来的生日