LoginSignup
2
3

More than 5 years have passed since last update.

pythonで多次元リストの引き算をする(備忘録)

Posted at

(ただの備忘録)
多次元リストの扱いに少々困ったので、残しておきます。
まずは一次元のリストの引き算は以下のように出来ます。

A = [1, 2, 3]
B = [1, 4]
print(list(set(A)-set(B)))
# [2, 3]

2次元リストでも同じように行けるかな?と思いやってみると

C = [[1, 1], [1, 2], [1, 3]]
D = [[1, 1], [1, 4]]
print(list(set(C)-set(D)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

こんな感じで怒られます。

どうすれば良いと思う?
と調べているとmapを使えば出来ました。

E = list(map(list, list(set(map(tuple, C)) - set(map(tuple, D)))))
print(E)
# [[1, 2], [1, 3]]

listはunhashableだけど、tupleはhashableなんですね。
知らなかったです。

2
3
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
2
3