LoginSignup
5
2

More than 5 years have passed since last update.

【Python基礎】set型(セット型)の使い方

Last updated at Posted at 2018-11-22

1. セット型(set)とは

  • セットはPythonで扱える集合を表すデータ型である。
  • リスト等と同様に複数の要素をもつことが可能。
  • 集合なので、リストとは異なり要素は順番がない。
  • 重複した要素は取り除かれる。

2. "あいうえお"を例に見てみる

words = "あいうえお"
#文字数を見る
print("文字の数は"+ str(len(words))+"だよ")
#文字の種類を洗い出す
print("文字の種類は"+ str(set(words))+"だよ")
#文字の種類の数を数える
print("文字の種類の数は"+ str(len(set(words)))+"だよ")

文字の数は5だよ
文字の種類は{'え', 'う', 'お', 'あ', 'い'}だよ
文字の種類の数は5だよ

words = "あいうえお"
#文字数を見る
print("文字の数は"+ str(len(words))+"だよ")
#文字の種類を洗い出す
print("文字の種類は"+ str(set(words))+"だよ")
#文字の種類の数を数える
print("文字の種類の数は"+ str(len(set(words)))+"だよ")

3. "ぼぼぼーぼぼーぼぼ"を例に見てみる

words = "ぼぼぼーぼぼーぼぼ"
#文字数を見る
print("文字の数は"+ str(len(words))+"だよ")
#文字の種類を洗い出す
print("文字の種類は"+ str(set(words))+"だよ")
#文字の種類の数を数える
print("文字の種類の数は"+ str(len(set(words)))+"だよ")

文字の数は9だよ
文字の種類は{'ー', 'ぼ'}だよ
文字の種類の数は2だよ

おまけ 改行を含めた文章(今回は"すもももももももものうち")を例に見てみる

#改行を含めたテキストを代入するために"を3つずつでくくる
words = """すももも
ももも
もものうち"""
#文字数を見る
print("文字の数は"+ str(len(words))+"だよ")
#文字の種類を洗い出す
print("文字の種類は"+ str(set(words))+"だよ")
#文字の種類の数を数える
print("文字の種類の数は"+ str(len(set(words)))+"だよ")

文字の数は14だよ
文字の種類は{'う', 'ち', 'の', 'す', 'も', '\n'}だよ
文字の種類の数は6だよ

改行も一文字としてカウントされましたね!

5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2