python中filter和切片實現回文函式

2021-10-03 08:13:18 字數 1451 閱讀 1657

一、回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數。

1.下面是我的**:

#!usr/bin/env python3

#-*- coding=utf -8-*-

#回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數

def is_palindrome(n):

s = str(n) #另:對str也可以進行切片,和list方法一樣

a = 0

if len(s) ==1:

return n

elif a <= len(s)/2:

if s[a] == s[len(s)-a-1]:

a = a+1

return n

output = filter(is_palindrome,range(1,1002))

print('1~100:',list(output))

2.下面是大神**,最終的效果都是一樣的:

#!usr/bin/env python3

#-*- coding=utf -8-*-

#回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數

def is_palindrome(n):

return str(n) == str(n)[::-1]

output = filter(is_palindrome, range(1,1002))

print('1~1002:',list(output))

3.大神的**不好理解,來複習下python中[-1]、[:-1]、[::-1]、[n::-1]使用方法

#!usr/bin/env python3

#-*- coding=utf -8-*-

import numpy as np

a = np.random.rand(5)

print(a)

[0.64061262 0.8451399 0.965673 0.89256687 0.48518743]

print(a[-1]) ###取最後乙個元素

[0.48518743]

print(a[:-1]) ### 除了最後乙個取全部

[0.64061262 0.8451399 0.965673 0.89256687]

print(a[::-1]) ### 取從後向前(相反)的元素

[0.48518743 0.89256687 0.965673 0.8451399 0.64061262]

print(a[2::-1]) ### 取從下標為2的元素翻轉讀取

[0.965673 0.8451399 0.64061262]

Python中filter與lambda的結合使用

filter是python的內建方法。官方定義是 filter function or none,sequence list,tuple,or string return those items of sequence for which function item is true.if funct...

python中的filter 函式

接收兩個引數,乙個函式 f和乙個list,這個函式 f對list中 的每個元素進行判斷,返回true或false,filter 根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件的元素組成的新的list。舉個例子 例如,要從乙個list 1,4,6,7,9,12,17 中刪除偶數,保留奇數,首先...

python中的filter 函式

1.語法 filter 函式用於過濾序列,過濾掉不符合條件的元素,返回符合條件的元素組成新列表 filter function,fiterable function 函式,fiterable為序列序列中的每個元素作為引數傳遞給函式進行判斷,返回true或者false,最後將會返回true的元素放到新...