Python 程式, 可過濾給定序列中的平方數


輸入

假設您有一個序列,

0    14
1    16
2    30
3    49
4    80

輸出

平方數元素的結果是,

0    4
1    16
3    49

解決方案 1

我們可以使用正則表示式和 lambda 函式 filter 方法查詢平方數的值。

  • 定義一個系列。

  • 應用 lambda filter 方法檢查值是否是平方數。定義如下,

   l = [14,16,30,49,80]
   data=pd.Series([14,16,30,49,80])
   result =pd.Series(filter(lambda x: x==int(m.sqrt(x)+0.5)**2,l))
  • 最後,使用 isin() 函式檢查值列表以檢視系列。

示例

import pandas as pd
import math as m
l = [4,16,30,49,80]
data = pd.Series(l)
print(data)
lis = []
for i in range(len(data)):
   for j in data:
      if(data[i]==int(m.sqrt(j)+0.5)**2):
         lis.append(data[i])
print(“Perfect squares in the series: \n”, data[data.isin(lis)])

輸出

Given series:
0    4
1    16
2    30
3    49
4    80
dtype: int64
Perfect Squares in the series:
0    4
1    16
3    49
dtype: int64

解決方案 2

示例

import re
import math as m
l = [14,16,30,49,80]
data = pd.Series([14,16,30,49,80])
print(“Given series:\n”, data)
result = pd.Series(filter(lambda x: x==int(m.sqrt(x)+0.5)**2,l))
print(data[data.isin(result)])

輸出

Given series:
0    14
1    16
2    30
3    49
4    80
dtype: int64
Perfect squares:
1    16
3    49
dtype: int64

更新於: 24-Feb-2021

498 次瀏覽

啟動你的職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.