用 Python 编写一个程序来过滤给定系列中的阿姆斯特朗数字
pythonpandasserver side programmingprogramming更新于 2024/6/21 0:44:17
假设您有一个系列和过滤阿姆斯特朗数字的结果,
原始系列为 0 153 1 323 2 371 3 420 4 500 dtype: int64 Armstrong 数字为:- 0 153 2 371 dtype: int64
为了解决这个问题,我们将遵循下面给出的步骤 −
定义一个系列。
创建一个空列表并设置 for 循环以访问所有系列数据。
将 armstrong 初始值设置为 0,并创建 temp 变量以逐个存储系列元素。它定义如下,
l = [] for val in data: armstrong = 0 temp = val
创建 while 循环并检查 temp>0 并通过 temp%10 计算余数。通过取余数的立方来添加 armstrong 值,然后将 temp 值除以 10,直到达到 0 以终止循环。其定义如下,
while(temp>0): rem = temp % 10 armstrong = armstrong + (rem**3) temp = temp // 10
设置 if 条件以将原始值与 temp 值进行比较。如果匹配,则将值附加到列表中。
if(armstrong==val): l.append(val)
最后,使用 isin() 检查系列中存在的列表值。它定义如下,
data[data.isin(l)]
示例
让我们看看下面的代码以获得更好的实现 −
import pandas as pd
data = pd.Series([153,323,371,420,500])
print("original series is\n", data)
l = []
for val in data:
armstrong = 0
temp = val
while(temp>0):
rem = temp % 10
armstrong = armstrong + (rem**3)
temp = temp // 10
if(armstrong==val):
l.append(val)
print("Armstrong 数字为:-")
print(data[data.isin(l)])
输出
原始系列为 0 153 1 323 2 371 3 420 4 500 dtype: int64 Armstrong 数字为:- 0 153 2 371 dtype: int64
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

