0
0

More than 1 year has passed since last update.

pythonの連想配列で存在しないキーを取得したい。

Last updated at Posted at 2023-02-08

例えば、リスト1、リスト2の2つが存在していて、リスト1に存在しないリスト2の要素を
リスト1に追加した新たなリストを作りたい。
ハッシュマップを使って高速に探索する。
list1 =["a","b","c"]
list2=["a","c","d"]
hashmap = {}
list3= []

# リストにある要素を連想配列に追加
for i in list2:
    hashmap[i] = i

# 連想配列にない要素を追加
#補足 get()は第2引数を持たせることでkeyがない場合のreturnを指定できる。
for i in list1:
    if hashmap.get(i) is None: list3.append(i)


#コメントより
# 連想配列にない要素を追加
for item in list1:
    if item not in hashmap: list3.append(i)
0
0
3

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
0
0