30秒学会 Python 片段 · 2023年9月8日

30秒学会 Python 片段 – List symmetric difference

Returns the symmetric difference between two iterables, without filtering out duplicate values.

  • Create a set from each list.
  • Use a list comprehension on each of them to only keep values not contained in the previously created set of the other.

代码实现

def symmetric_difference(a, b):
  (_a, _b) = (set(a), set(b))
  return [item for item in a if item not in _b] + [item for item in b
          if item not in _a]

使用样例

symmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4]

翻译自:https://www.30secondsofcode.org/python/s/symmetric-difference