高校物理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 の map でリストに関数を適用しよう

数を 2 乗する関数 square を例に、Python の map について考える。

def square(x):
	return x * x


m = 5
n = square(m)

print(n)
# 25

この平凡な関数をリストに適用したいとする。つまり

としたい。これは map で実現される。

def square(x):
	return x * x


a = [1, 2, 3, 4]
b = list(map(square, a))

print(b)
# [1, 4, 9, 16]

list に map を入れ、その中に適用したい関数、適用したいリストを入れる。

例:文字列のリストから、それぞれの文字数を出力するコード

a = ['apple', 'mac', 'google', 'e', '']
b = list(map(len, a))

print(b)
# [5, 3, 6, 1, 0]

新しい関数を作る必要はない。文字列のカウントは len であり、それを map に入れるだけである。