logo

【初心者】Pythonで大量の文字列の重複チェックをする方法【備忘録】

投稿日2023-02-06

更新日2024-05-17

Picture of the logo

タグ一覧

目次(タップして移動)

Pythonの豆知識、備忘録です。

重複の有無のチェック

Pythonで大量の文字列の重複チェックをするには、「集合」を使うのが良いようです。集合は重複した要素を自動的に削除してくれるため、文字列の重複チェックに特に向いています。

例えば、文字列のリストを集合に変換してから、新しい文字列を追加した場合に重複があるかどうかを判定することができます。

string_list = ["apple", "banana", "orange", "apple"]
string_set = set(string_list)

new_string = "apple"
if new_string in string_set:
    print("The string is already in the list.")
else:
    print("The string is not in the list.")

重複の制限

また、文字列のリストを集合に変換した後、新しい文字列を追加し、重複があった場合には、新しい文字列を追加しないこともできます。

string_list = ["apple", "banana", "orange", "apple"]
string_set = set(string_list)
new_string = "apple"
string_set.add(new_string)
print(string_set)





このサイトをシェアする