高校化学2924392 views
りんご209490 views
中学理科1630641 views
中学英語811710 views
雑学1473612 views
いろは3010814 views
世界の国564520 views
ヒストリア290598 views
高校生物551766 views
高校倫理1440106 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingMarkdown TablesSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/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 NetsRolling DiceCross SectionsMotion PathMechanicsWavesElectromagnetic WavesCapacitorsLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHOrganic Reaction MapPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionHormones and HomeostasisRock 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 TheoryShogi StrategyPiano Rhythm Game

English

Pythonのラムダ(lambda)式関数とはなにか?sorted や map と一緒に使う方法

Python の lambda 式は次のように使います。

add = lambda x, y: x + y

print(add(3, 5))
# 8

これだけだと「通常の関数定義とどう違うの?」と思いますね。下のコードを見ると、だんだんラムダ式の利便性がわかってきます。

cities = ["London", "Tokyo", "New York", "Oslo", "Berlin"]

sorted_cities = sorted(cities, key=lambda city: len(city))

print(sorted_cities)
# ['Oslo', 'Tokyo', 'London', 'Berlin', 'New York']

文字列の長さを返す関数をラムダ式としてつくったものの、名前はありません。上のような関数を無名関数といいます。ラムダ式は sorted の条件として使われています。

ラムダ式は map とも相性がいい。

nums = [1, 2, 3, 4]

doubled = list(map(lambda x: x * 2, nums))

print(doubled)
# [2, 4, 6, 8]

map は、リストなどの各要素に、同じ関数を適用して新しいリスト(的なもの)をつくります。

リストからリストをつくる、とイメージしてもいいです。ただし、できあがるものはリストそのものではありません。

nums = [1, 2, 3, 4]

result = map(lambda x: x * 2, nums)
doubled = list(result)

print(result)
# <map object at 0x102415840>

print(type(result))
# <class 'map'>

print(doubled)
# [2, 4, 6, 8]

map は map オブジェクトを返し、要素を具体的に抽出するにはリストへキャストします。