Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
セット
セットは重複のないリストです。たとえば、段落内で使用されている単語のリストを集めたいとしましょう。
print(set("my name is Eric and Eric is my name".split()))
これは「my」、「name」、「is」、「Eric」、そして最後に「and」を含むリストを出力します。文の他の単語はすでにセットに含まれているため、重複して挿入されません。
Pythonにおいてセットは強力なツールです。なぜなら、他のセット間での差分や共通部分を計算する能力があるからです。たとえば、イベントAとBの参加者のリストがあるとします:
a = set(["Jake", "John", "Eric"])
print(a)
b = set(["John", "Jill"])
print(b)
両方のイベントに参加したメンバーを見つけるには、「intersection」メソッドを使用します:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.intersection(b))
print(b.intersection(a))
どちらか片方のイベントにのみ参加したメンバーを見つけるには、「symmetric_difference」メソッドを使用します:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.symmetric_difference(b))
print(b.symmetric_difference(a))
一方のイベントには参加したが、もう一方には参加していないメンバーを見つけるには、「difference」メソッドを使用します:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.difference(b))
print(b.difference(a))
全参加者のリストを取得するには、「union」メソッドを使用します:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.union(b))
以下の演習では、指定されたリストを使用して、イベントAからイベントBに参加しなかった全参加者を含むセットを出力してみてください。
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
A = set(a)
B = set(b)
print(A.difference(B))
test_output_contains("['Jake', 'Eric']")
success_msg("Nice work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!