いろは3010814 views
英語613639 views
高校化学2924392 views
ヒストリア290598 views
中学理科1630641 views
教育149510 views
高校国語788336 views
小学算数1200427 views
高校倫理1440106 views
数学講師2886227 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 の集合(要素の存在、追加、削除)

集合と辞書は似ています。

fruits = {'apple', 'melon', 'peach'}

print(type(fruits))  # <class 'set'>
print(len(fruits))  # 3

data = {'Alice': 27, 'Bob': 35}

print(type(data))  # <class 'dict'>
print(len(data))  # 2

コロンを使わず、要素を並べたものは集合になります。集合は順序を持たないため、下のコードは実行するたびに異なる結果を出力します。

fruits = {'apple', 'melon', 'peach'}

print(fruits)

集合の要素になりうるもの

students = {['Alice', 27], 'Bob'}

print(students)
# TypeError: unhashable type: 'list'

リスト、辞書、集合といった unhashable なものは集合の要素になりません。リストの集合、辞書の集合、集合の集合はない、ということです。

集合の要素は hashable である必要があります。整数、浮動小数点数、ブール値、文字列、そしてタプルは hashable です。

items = {-100, 3.14, True, 'Alice', ('Roll', 'Pie')}

print(items)

if ('Roll', 'Pie') in items:
	print('ロールパイ')
else:
	print('No')

要素の存在を確認する

students = {'Alice', 'Bob'}

if 'Alice' in students:
	print('Exist')
else:
	print('No')

集合に要素を追加する

items = {1, 2}

items.add(3)

print(items)
# {1, 2, 3}

items.add(2)

print(items)
# {1, 2, 3}

すでに存在する要素を追加しても、集合は変わりません。集合に集合を追加するには update を使います。

items = {1, 2}
others = {3, 4}

items.update(others)

print(items)
# {1, 2, 3, 4}

print(others)
# {3, 4}

集合から要素を削除する

items = {1, 2, 3, ('roll', 'pie')}

items.remove(1)

print(items)
# {2, 3, ('roll', 'pie')}

items.remove(('roll', 'pie'))

print(items)
# {2, 3}

存在しないものを削除するとエラーが起きます。

items = {1, 2, 3, ('roll', 'pie')}

items.remove(100)
# KeyError: 100

存在するかわからないものを削除したいときは discard を使います。

items = {1, 2, 3, ('roll', 'pie')}

items.discard(('roll', 'pie'))

print(items)
# {3, 1, 2}

items.discard(100)

print(items)
# {3, 1, 2}
Python の集合は順序のない要素の集まりです。