高校物理160203 views
高校国語788336 views
高校化学2924392 views
雑学1473612 views
高校日本史190571 views
小学社会310485 views
英語613639 views
小学算数1200427 views
りんご209490 views
高校生物551766 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic Theory

English

Pythonのfilterを使う:リストから条件に合う要素を削除しよう

Python でリストから特定の要素を削除したいときは filter を使う。

def has_many_letters(str):
c = len(str)
if c > 3:
return True
else:
return False

a = [‘apple’, ‘mac’, ‘google’, ‘e’, ‘’]
b = list(filter(has_many_letters, a))

print(b)

[‘apple’, ‘google’]

ポイントは filter で、これはリストから条件に合う要素を削除する。条件、リストの順に入れる。

filter(条件, リスト)

条件はだいたい関数である。上の Python コードでは、最初に定義された has_many_letters が条件に当たる。これは文字列の長さ(文字数)が 3 より多かったら真、それ以外で偽を返す。

条件にする関数はあくまでも個別の値に対する関数である。

Python の filter に入れる引数はカッコをつけない

Python の filter に入れる関数は名前のみを記し、カッコをつけない。次のコードは誤り。

b = list(filter(has_many_letters(), a))

カッコを入れると

Traceback (most recent call last):
File “/PycharmProjects/example/test.py”, line 9, in
b = list(filter(is_mod3(), a))
TypeError: is_mod3() missing 1 required positional argument: ‘num’

のようなメッセージが出る。ちなみに PycharmProjects は Python を書くためのソフト。

filter の前についている list をとったらどうなるか

出力されるものの変化を見てみよう。

def has_many_letters(str):
c = len(str)
if c > 3:
return True
else:
return False

a = [‘apple’, ‘mac’, ‘google’, ‘e’, ‘’]
b = filter(has_many_letters, a)

print(b)

<filter object at 0x10dd2c0f0>

filter object at 0x10dd2c0f0 という謎のものが出力された。これは文字どおり filter object というもので、使いにくい。だから最初のコードのように

list(filter(…))

と list をつける。

Python プログラミングの問題

リストから 3 の倍数を削除する Python プログラムを書きなさい。

答え

def is_mod3(num):
if num % 3 == 0:
return False
else:
return True

a = [2, 3, 5, 6, 7]
b = list(filter(is_mod3, a))

print(b)

[2, 5, 7]

Python の mod 計算(余りを求める計算)は

num % 3

のようにする。

Pythonのfilterの使い方。filterはPythonのリストから特定の条件に合う要素を削除する。filterには適用したい関数とリストを順に入れる。