programing

고유 엔트리가 있는 두 목록 간의 차이점 가져오기

elseif 2023. 4. 19. 22:27

고유 엔트리가 있는 두 목록 간의 차이점 가져오기

Python에는 다음 두 가지 목록이 있습니다.

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

각 목록의 요소가 고유하다고 가정하면 두 번째 목록에 없는 첫 번째 목록의 항목을 사용하여 세 번째 목록을 만듭니다.

temp3 = ['Three', 'Four']

사이클과 점검 없이 빠른 방법이 있습니까?

temp1 에는 temp2( 목록에 있는 요소의 고유성 확인):

In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']

비대칭인 것에 주의해 주세요.

In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1]) 

set([1, 3])원한다면set([1, 3])당신의 답변으로, 당신은 사용할 수 있습니다.set([1, 2]).symmetric_difference(set([2, 3])).

기존 솔루션은 모두 다음 중 하나를 제공합니다.

  • O(n*m) 퍼포먼스보다 빠릅니다.
  • 입력 목록의 순서를 유지합니다.

하지만 지금까지 그 어떤 해결책도 둘 다 가지고 있지 않습니다.둘 다 필요한 경우 다음을 수행합니다.

s = set(temp2)
temp3 = [x for x in temp1 if x not in s]

퍼포먼스 테스트

import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)
print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)
print timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)

결과:

4.34620224079 # ars' answer
4.2770634955  # This answer
30.7715615392 # matt b's answer

제가 제시한 방법이나 순서를 유지하는 방법도 불필요한 세트를 만들 필요가 없기 때문에 (약간) 감산보다 빠릅니다.첫 번째 목록이 두 번째 목록보다 상당히 길고 해시가 비쌀 경우 성과 차이가 더 두드러질 것이다.다음은 이를 입증하는 두 번째 테스트입니다.

init = '''
temp1 = [str(i) for i in range(100000)]
temp2 = [str(i * 2) for i in range(50)]
'''

결과:

11.3836875916 # ars' answer
3.63890368748 # this answer (3 times faster!)
37.7445402279 # matt b's answer

python XOR 연산자를 사용하여 수행할 수 있습니다.

  • 그러면 각 목록의 중복 항목이 제거됩니다.
  • 이것은 temp1과 temp2의 차이를 나타내고 temp2와 temp1의 차이를 나타냅니다.

set(temp1) ^ set(temp2)

목록 이해를 사용할 수 있습니다.

temp3 = [item for item in temp1 if item not in temp2]

이것을 시험해 보세요.

temp3 = set(temp1) - set(temp2)

재귀적으로 차이를 원하시면 python용 패키지를 작성했습니다.https://github.com/seperman/deepdiff

인스톨

PyPi에서 설치:

pip install deepdiff

사용 예

Import 중

>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2

동일한 개체가 빈 상태로 반환됨

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}

품목 유형이 변경되었습니다.

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
                                 'newvalue': '2',
                                 'oldtype': <class 'int'>,
                                 'oldvalue': 2}}}

품목 값이 변경되었습니다.

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

아이템 추가 및/또는 삭제

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
 'dic_item_removed': ['root[4]'],
 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

문자열의 차이

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
                      "root[4]['b']": { 'newvalue': 'world!',
                                        'oldvalue': 'world'}}}

문자열 차이 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
                                                '+++ \n'
                                                '@@ -1,5 +1,4 @@\n'
                                                '-world!\n'
                                                '-Goodbye!\n'
                                                '+world\n'
                                                ' 1\n'
                                                ' 2\n'
                                                ' End',
                                        'newvalue': 'world\n1\n2\nEnd',
                                        'oldvalue': 'world!\n'
                                                    'Goodbye!\n'
                                                    '1\n'
                                                    '2\n'
                                                    'End'}}}

>>> 
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
--- 
+++ 
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
 1
 2
 End

유형 변경

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
                                      'newvalue': 'world\n\n\nEnd',
                                      'oldtype': <class 'list'>,
                                      'oldvalue': [1, 2, 3]}}}

리스트의 차이

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}

목록 차이 2:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
  'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
                      "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}

목록 차이 무시 순서 또는 중복: (위 사전과 동일)

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}

사전이 포함된 목록:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
  'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}

세트:

>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}

명명된 튜플:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}

커스텀 오브젝트:

>>> class ClassA(object):
...     a = 1
...     def __init__(self, b):
...         self.b = b
... 
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>> 
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

추가된 개체 특성:

>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

두 목록(list1과 list2)의 차이는 다음과 같은 간단한 함수를 사용하여 확인할 수 있습니다.

def diff(list1, list2):
    c = set(list1).union(set(list2))  # or c = set(list1) | set(list2)
    d = set(list1).intersection(set(list2))  # or d = set(list1) & set(list2)
    return list(c - d)

또는

def diff(list1, list2):
    return list(set(list1).symmetric_difference(set(list2)))  # or return list(set(list1) ^ set(list2))

함수를 알수.diff(temp2, temp1) ★★★★★★★★★★★★★★★★★」diff(temp1, temp2) 둘 다 를 줄 예요.['Four', 'Three']리스트의 순서나 어떤 리스트가 먼저 주어질지 신경 쓰지 않아도 됩니다.

Python 문서 참조

가장 간단한 방법

setsecretence(set)사용합니다.

list_a = [1,2,3]
list_b = [2,3]
print set(list_a).difference(set(list_b))

은 「」입니다.set([1])

목록으로 인쇄할 수 있습니다.

print list(set(list_a).difference(set(list_b)))

현재의 솔루션 중 태플을 산출하는 것은 없기 때문에, 토스하겠습니다.

temp3 = tuple(set(temp1) - set(temp2))

또는 다음과 같이 입력합니다.

#edited using @Mark Byers idea. If you accept this one as answer, just accept his instead.
temp3 = tuple(x for x in temp1 if x not in set(temp2))

이 방향에서 답을 내는 다른 비태플과 마찬가지로 질서를 유지합니다.

퍼포먼스를 정말 원한다면 numpy를 사용하세요!

목록, numpy, panda의 비교에 대한 github의 요지로서 여기 전체 수첩이 있습니다.

https://gist.github.com/denfromufa/2821ff59b02e9482be15d27f2bbd4451

여기에 이미지 설명 입력

는 두 , 을 할 수 있는지 할 수 있는 것은 할 수 .diffbash이 질문은 '피톤 diff 2 lists'를 검색할 때 가장 먼저 뜨는 질문이고 구체적이지 않기 때문에 제가 생각해낸 것을 올리도록 하겠습니다.

사용처difflib 두 할 수 있습니다.diff다른 답변은 차이가 발생하는 위치를 알려주지 않지만, 이번 답변은 차이가 발생하는 위치를 알려준다.일부 답변은 한 방향으로만 차이를 제공합니다.이치노복제품을 취급하지 않는 사람도 있습니다.그러나 이 솔루션은 두 가지 목록 간에 진정한 차이를 제공합니다.

a = 'A quick fox jumps the lazy dog'.split()
b = 'A quick brown mouse jumps over the dog'.split()

from difflib import SequenceMatcher

for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
  if tag == 'equal': print('both have', a[i:j])
  if tag in ('delete', 'replace'): print('  1st has', a[i:j])
  if tag in ('insert', 'replace'): print('  2nd has', b[k:l])

출력은 다음과 같습니다.

both have ['A', 'quick']
  1st has ['fox']
  2nd has ['brown', 'mouse']
both have ['jumps']
  2nd has ['over']
both have ['the']
  1st has ['lazy']
both have ['dog']

물론 다른 답변과 동일한 가정을 응용 프로그램이 하는 경우 가장 큰 혜택을 볼 수 있습니다.하지만 만약 당신이 진실을 찾고 있다면diff을 사용하다

예를 들어, 다른 답변은 모두 다음을 처리할 수 없었습니다.

a = [1,2,3,4,5]
b = [5,4,3,2,1]

하지만 이건 그렇다.

  2nd has [5, 4, 3, 2]
both have [1]
  1st has [2, 3, 4, 5]

ㅇㅇㅇㅇㅇㅇㄹ게요.Counter장장간간간경경경경경경경

이는 질문의 내용과 정확히 일치하기 때문에 양방향 차이를 보이는 위의 목록보다 짧습니다. 즉, 첫 번째 목록에는 있지만 두 번째 목록에는 없는 목록만 생성하기 때문입니다.

from collections import Counter

lst1 = ['One', 'Two', 'Three', 'Four']
lst2 = ['One', 'Two']

c1 = Counter(lst1)
c2 = Counter(lst2)
diff = list((c1 - c2).elements())

또는 가독성 기호에 따라 적절한 원라이너로 만들 수 있습니다.

diff = list((Counter(lst1) - Counter(lst2)).elements())

출력:

['Three', 'Four']

, 이 경우 합니다.list(...)★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

이 솔루션은 카운터를 사용하기 때문에 다수의 세트 기반 응답에 비해 수량을 적절하게 처리합니다.예를 들어, 이 입력은 다음과 같습니다.

lst1 = ['One', 'Two', 'Two', 'Two', 'Three', 'Three', 'Four']
lst2 = ['One', 'Two']

출력은 다음과 같습니다.

['Two', 'Two', 'Three', 'Three', 'Four']

마크의 목록 이해보다 더 빠를 수 있습니다.

list(itertools.filterfalse(set(temp2).__contains__, temp1))

다음으로 2개의 문자열 목록을 구분하는 간단한 순서를 유지하는 방법을 몇 가지 나타냅니다.

코드

다음을 사용한 특이한 접근법:

import pathlib


temp1 = ["One", "Two", "Three", "Four"]
temp2 = ["One", "Two"]

p = pathlib.Path(*temp1)
r = p.relative_to(*temp2)
list(r.parts)
# ['Three', 'Four']

이 경우 두 목록 모두 시작이 동일한 문자열이 포함되어 있다고 가정합니다.상세한 것에 대하여는, 문서를 참조해 주세요.설정 조작에 비해 특별히 빠른 것은 아닙니다.


다음을 사용한 간단한 구현:

import itertools as it


[x for x, y in it.zip_longest(temp1, temp2) if x != y]
# ['Three', 'Four']

다음은 @SuperNova의 답변 수정 버전입니다.

def get_diff(a: list, b: list) -> list:
    return list(set(a) ^ set(b))

arulmr 용액의 한 줄 버전

def diff(listA, listB):
    return set(listA) - set(listB) | set(listB) -set(listA)

이것은 또 다른 해결책입니다.

def diff(a, b):
    xa = [i for i in set(a) if i not in b]
    xb = [i for i in set(b) if i not in a]
    return xa + xb

difflist의 요소가 정렬되어 설정되어 있는 경우, 순진한 방법을 사용할 수 있습니다.

list1=[1,2,3,4,5]
list2=[1,2,3]

print list1[len(list2):]

또는 네이티브 설정 방식:

subset=set(list1).difference(list2)

print subset

import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print "Naive solution: ", timeit.timeit('temp1[len(temp2):]', init, number = 100000)
print "Native set solution: ", timeit.timeit('set(temp1).difference(temp2)', init, number = 100000)

간단한 솔루션: 0.0787101593292

네이티브 세트 솔루션: 0.998837615564

게임에는 조금 늦었지만, 위의 코드 중 몇 가지를 이것과 비교할 수 있습니다.가장 빠른 경쟁자 중 두 가지는 다음과 같습니다.

list(set(x).symmetric_difference(set(y)))
list(set(x) ^ set(y))

초급 코딩에 대해 사과드립니다.

import time
import random
from itertools import filterfalse

# 1 - performance (time taken)
# 2 - correctness (answer - 1,4,5,6)
# set performance
performance = 1
numberoftests = 7

def answer(x,y,z):
    if z == 0:
        start = time.clock()
        lists = (str(list(set(x)-set(y))+list(set(y)-set(y))))
        times = ("1 = " + str(time.clock() - start))
        return (lists,times)

    elif z == 1:
        start = time.clock()
        lists = (str(list(set(x).symmetric_difference(set(y)))))
        times = ("2 = " + str(time.clock() - start))
        return (lists,times)

    elif z == 2:
        start = time.clock()
        lists = (str(list(set(x) ^ set(y))))
        times = ("3 = " + str(time.clock() - start))
        return (lists,times)

    elif z == 3:
        start = time.clock()
        lists = (filterfalse(set(y).__contains__, x))
        times = ("4 = " + str(time.clock() - start))
        return (lists,times)

    elif z == 4:
        start = time.clock()
        lists = (tuple(set(x) - set(y)))
        times = ("5 = " + str(time.clock() - start))
        return (lists,times)

    elif z == 5:
        start = time.clock()
        lists = ([tt for tt in x if tt not in y])
        times = ("6 = " + str(time.clock() - start))
        return (lists,times)

    else:    
        start = time.clock()
        Xarray = [iDa for iDa in x if iDa not in y]
        Yarray = [iDb for iDb in y if iDb not in x]
        lists = (str(Xarray + Yarray))
        times = ("7 = " + str(time.clock() - start))
        return (lists,times)

n = numberoftests

if performance == 2:
    a = [1,2,3,4,5]
    b = [3,2,6]
    for c in range(0,n):
        d = answer(a,b,c)
        print(d[0])

elif performance == 1:
    for tests in range(0,10):
        print("Test Number" + str(tests + 1))
        a = random.sample(range(1, 900000), 9999)
        b = random.sample(range(1, 900000), 9999)
        for c in range(0,n):
            #if c not in (1,4,5,6):
            d = answer(a,b,c)
            print(d[1])

예를 들어 두 개의 리스트가 있다고 합시다.

list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 4, 5]

위의 두 가지 목록에서 1, 3, 5번 항목이 list2에 존재하고 7, 9번 항목이 존재하지 않음을 알 수 있습니다.한편 list1에는 1, 3, 5항목이 존재하지만 2, 4항목이 존재하지 않는다.

항목 7, 9, 2, 4가 포함된 새 목록을 반환하는 가장 좋은 솔루션은 무엇입니까?

위의 모든 답변에서 해결 방법을 찾을 수 있습니다. 이제 가장 적합한 것은 무엇입니까?

def difference(list1, list2):
    new_list = []
    for i in list1:
        if i not in list2:
            new_list.append(i)

    for j in list2:
        if j not in list1:
            new_list.append(j)
    return new_list

def sym_diff(list1, list2):
    return list(set(list1).symmetric_difference(set(list2)))

시간을 이용하여 결과를 볼 수 있습니다.

t1 = timeit.Timer("difference(list1, list2)", "from __main__ import difference, 
list1, list2")
t2 = timeit.Timer("sym_diff(list1, list2)", "from __main__ import sym_diff, 
list1, list2")

print('Using two for loops', t1.timeit(number=100000), 'Milliseconds')
print('Using two for loops', t2.timeit(number=100000), 'Milliseconds')

돌아온다

[7, 9, 2, 4]
Using two for loops 0.11572412995155901 Milliseconds
Using symmetric_difference 0.11285737506113946 Milliseconds

Process finished with exit code 0

에 부딪히면TypeError: unhashable type: 'list'목록 또는 세트를 튜플로 변환해야 합니다.

set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))

참고 항목: python에서 목록/세트 목록을 비교하는 방법

집합으로 변환한 후 "difference()" 함수를 사용하는 것이 좋습니다.전체 코드는 다음과 같습니다.

temp1 = ['One', 'Two', 'Three', 'Four'  ]                   
temp2 = ['One', 'Two']
set1 = set(temp1)
set2 = set(temp2)
set3 = set1.difference(set2)
temp3 = list(set3)
print(temp3)

출력:

>>>print(temp3)
['Three', 'Four']

이 방법은 언더앤딩이 가장 용이하며, 향후 대용량 데이터를 사용하는 경우 세트로 변환하면 중복이 필요하지 않은 경우 중복이 제거됩니다.도움이 되었으면 좋겠다;-)

목록 b에 있는 모든 값을 목록a에서 삭제해야 하는 경우.

def list_diff(a, b):
    r = []

    for i in a:
        if i not in b:
            r.append(i)
    return r

list_diff([1, 2, 2], [1])

결과: [2,2]

또는

def list_diff(a, b):
    return [x for x in a if x not in b]

변화 세트 같은 걸 원하신다면...카운터를 사용할 수 있습니다.

from collections import Counter

def diff(a, b):
  """ more verbose than needs to be, for clarity """
  ca, cb = Counter(a), Counter(b)
  to_add = cb - ca
  to_remove = ca - cb
  changes = Counter(to_add)
  changes.subtract(to_remove)
  return changes

lista = ['one', 'three', 'four', 'four', 'one']
listb = ['one', 'two', 'three']

In [127]: diff(lista, listb)
Out[127]: Counter({'two': 1, 'one': -1, 'four': -2})
# in order to go from lista to list b, you need to add a "two", remove a "one", and remove two "four"s

In [128]: diff(listb, lista)
Out[128]: Counter({'four': 2, 'one': 1, 'two': -1})
# in order to go from listb to lista, you must add two "four"s, add a "one", and remove a "two"

교차점에서 목록의 합계를 뺀 값을 계산할 수 있습니다.

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']

set(temp1+temp2)-(set(temp1)&set(temp2))

Out: set(['Four', 'Five', 'Three']) 

이 질문은 이미 훌륭한 답변을 얻었지만 다음 방법을 추가하고자 합니다.numpy.

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

list(np.setdiff1d(temp1,temp2))

['Four', 'Three'] #Output

이것은 한 줄로 해결할 수 있다.질문에는 2개의 리스트(temp1 및 temp2)가 지정되어 있으며, 그 차이는 3번째 리스트(temp3)로 반환됩니다.

temp3 = list(set(temp1).difference(set(temp2)))

다음으로 2개의 리스트(내용에 관계없이)를 간단하게 구별하는 방법을 나타냅니다.다음과 같이 결과를 얻을 수 있습니다.

>>> from sets import Set
>>>
>>> l1 = ['xvda', False, 'xvdbb', 12, 'xvdbc']
>>> l2 = ['xvda', 'xvdbb', 'xvdbc', 'xvdbd', None]
>>>
>>> Set(l1).symmetric_difference(Set(l2))
Set([False, 'xvdbd', None, 12])

이것이 도움이 되기를 바랍니다.

첫 번째 목록을 순환하여 두 번째 목록에 없지만 첫 번째 목록에 있는 모든 항목에 대해 세 번째 목록에 추가할 수 있습니다.예:

temp3 = []
for i in temp1:
    if i not in temp2:
        temp3.append(i)
print(temp3)

목록이 원시 유형이 아닌 객체의 경우, 이는 한 가지 방법입니다.

코드가 더 명확하고 복사본을 제공합니다.이는 효율적인 구현은 아니지만 더 적은 개체 목록에 대해서는 깨끗합니다.

a = [
    {'id1': 1, 'id2': 'A'},
    {'id1': 1, 'id2': 'B'},
    {'id1': 1, 'id2': 'C'},  # out
    {'id1': 2, 'id2': 'A'},
    {'id1': 2, 'id2': 'B'},  # out
]
b = [
    {'id1': 1, 'id2': 'A'},
    {'id1': 1, 'id2': 'B'},
    {'id1': 2, 'id2': 'A'},
]


def difference(a, b):
  for x in a:
    for y in b:
      if x['id1'] == y['id1'] and x['id2'] == y['id2']:
        x['is_removed'] = True

  c = [x for x in a if not x.get('is_removed', False)]
  return c


print(difference(a, b))

언급URL : https://stackoverflow.com/questions/3462143/get-difference-between-two-lists-with-unique-entries