Usuwanie duplikatów na listach

W zasadzie muszę napisać program, aby sprawdzić, czy lista ma duplikaty, a jeśli tak, to usuwa je i zwraca nową listę z elementami, które nie były duplikowane/usunięte. To jest to, co mam, ale szczerze mówiąc Nie wiem, co robić.

def remove_duplicates():
    t = ['a', 'b', 'c', 'd']
    t2 = ['a', 'c', 'd']
    for t in t2:
        t.append(t.remove())
    return t
Author: Raymond Hettinger, 2011-11-01

30 answers

Powszechnym podejściem do uzyskania unikalnej kolekcji przedmiotów jest użycie set. Zbiory są nieuporządkowanymi zbiorami odrębnymi obiektami. Aby utworzyć zestaw z dowolnego iterable, możesz po prostu przekazać go do wbudowanego set() funkcja. Jeśli później znów będziesz potrzebował prawdziwej listy, możesz w podobny sposób przekazać zestaw do list() funkcja.

Poniższy przykład powinien obejmować wszystko, co próbujesz zrobić:

>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]

Jak widać z przykładowy wynik, oryginalna kolejność nie jest zachowana. Jak wspomniano powyżej, same zbiory są kolekcjami nieuporządkowanymi, więc kolejność jest tracona. Podczas konwersji zestawu z powrotem do listy tworzony jest dowolny porządek.

Jeśli zamówienie jest dla Ciebie ważne, będziesz musiał użyć innego mechanizmu. Bardzo powszechnym rozwiązaniem jest poleganie na OrderedDict aby zachować kolejność klawiszy podczas wstawiania:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(t))
[1, 2, 3, 5, 6, 7, 8]

Zauważ, że ma to na celu najpierw utworzenie słownika, a następnie tworzenie listy z niego. Więc jeśli nie musisz zachować porządku, lepiej używaj zestawu. Sprawdź to pytanie , aby uzyskać więcej szczegółów i alternatywne sposoby zachowania porządku podczas usuwania duplikatów.


Na koniec zauważ, że zarówno rozwiązanie set, jak i rozwiązanie OrderedDict wymagają, aby twoje przedmioty były hashable . Zazwyczaj oznacza to, że muszą być niezmienne. Jeśli masz do czynienia z elementami, które nie są hashable( np. lista obiektów), to będziesz musisz użyć powolnego podejścia, w którym będziesz musiał porównać każdy element z każdym innym elementem w zagnieżdżonej pętli.

 1136
Author: poke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-31 20:25:25

W Pythonie 2.7, nowy sposób usuwania duplikatów z iterowalnych przy zachowaniu pierwotnej kolejności to:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

W Pythonie 3.5, OrderedDict posiada implementację C. Moje timingi pokazują, że jest to teraz najszybsze i najkrótsze z różnych podejść do Pythona 3.5.

W Pythonie 3.6 , zwykły dict stał się zarówno uporządkowany, jak i zwarty. (Ta funkcja jest dostępna dla CPython i PyPy, ale może nie występować w innych implementacjach). Że daje nam nowy najszybszy sposób dedupowania przy zachowaniu porządku:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

W Pythonie 3.7 , zwykły dict jest gwarantowany dla obu uporządkowanych we wszystkich implementacjach. zatem najkrótszym i najszybszym rozwiązaniem jest:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']
 307
Author: Raymond Hettinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-22 08:26:41

To jednolinijkowy: list(set(source_list)) da radę.

A {[2] } jest czymś, co nie może mieć duplikatów.

Update: podejście zachowujące porządek to dwie linie:

from collections import OrderedDict
OrderedDict((x, True) for x in source_list).keys()

Tutaj używamy faktu, że OrderedDict zapamiętuje kolejność wstawiania kluczy i nie zmienia jej, gdy wartość w danym kluczu jest aktualizowana. Wstawiamy True jako wartości, ale możemy wstawić cokolwiek, wartości po prostu nie są używane. (set działa podobnie jak {[6] } z ignorowanymi wartościami.)

 161
Author: 9000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-05 16:39:17
>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> s = []
>>> for i in t:
       if i not in s:
          s.append(i)
>>> s
[1, 2, 3, 5, 6, 7, 8]
 69
Author: Neeraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-14 12:39:55

Jeśli nie zależy ci na zamówieniu, po prostu zrób to:

def remove_duplicates(l):
    return list(set(l))

A set gwarantuje, że nie będą miały duplikatów.

 63
Author: Brendan Long,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 00:49:08

Aby utworzyć nową listę zachowującą kolejność pierwszych elementów duplikatów w L

newlist=[ii for n,ii in enumerate(L) if ii not in L[:n]]

Na przykład if L=[1, 2, 2, 3, 4, 2, 4, 3, 5] wtedy newlist będzie [1,2,3,4,5]

Sprawdza, czy każdy nowy element nie pojawił się wcześniej na liście przed dodaniem go. Również nie wymaga importu.

 28
Author: Richard Fredlund,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-27 23:14:19

Inny sposób działania:

>>> seq = [1,2,3,'a', 'a', 1,2]
>> dict.fromkeys(seq).keys()
['a', 1, 2, 3]
 18
Author: James Sapam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-03 03:23:23

Kolega wysłał mi zaakceptowaną odpowiedź jako część kodu do codereview dzisiaj. Chociaż z pewnością podziwiam elegancję odpowiedzi na pytanie, nie jestem zadowolony z wykonania. Próbowałem tego rozwiązania (używam set aby skrócić czas wyszukiwania)

def ordered_set(in_list):
    out_list = []
    added = set()
    for val in in_list:
        if not val in added:
            out_list.append(val)
            added.add(val)
    return out_list

Aby porównać wydajność, użyłem losowej próbki 100 liczb całkowitych - 62 były unikalne

from random import randint
x = [randint(0,100) for _ in xrange(100)]

In [131]: len(set(x))
Out[131]: 62

Oto wyniki pomiarów

In [129]: %timeit list(OrderedDict.fromkeys(x))
10000 loops, best of 3: 86.4 us per loop

In [130]: %timeit ordered_set(x)
100000 loops, best of 3: 15.1 us per loop

Cóż, co się stanie, jeśli set zostanie usunięty z rozwiązanie?

def ordered_set(inlist):
    out_list = []
    for val in inlist:
        if not val in out_list:
            out_list.append(val)
    return out_list

Wynik nie jest tak zły jak w przypadku OrderedDict , ale nadal ponad 3 razy w stosunku do oryginalnego rozwiązania

In [136]: %timeit ordered_set(x)
10000 loops, best of 3: 52.6 us per loop
 17
Author: volcano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-17 09:52:45

Istnieją również rozwiązania wykorzystujące Pandy i Numpy. Obie zwracają tablicę numpy, więc trzeba użyć funkcji .tolist() jeśli chcesz listę.

t=['a','a','b','b','b','c','c','c']
t2= ['c','c','b','b','b','a','a','a']

Rozwiązanie Pandas

Używanie funkcji Pandy unique():

import pandas as pd
pd.unique(t).tolist()
>>>['a','b','c']
pd.unique(t2).tolist()
>>>['c','b','a']

Rozwiązanie Numpy

Używanie funkcji numpy unique().

import numpy as np
np.unique(t).tolist()
>>>['a','b','c']
np.unique(t2).tolist()
>>>['a','b','c']

Zauważ, że numpy.unique() sortuje również wartości . Tak więc lista t2 jest zwracana posortowana. Jeśli chcesz mieć zachowaną kolejność Użyj jak w ta odpowiedź :

_, idx = np.unique(t2, return_index=True)
t2[np.sort(idx)].tolist()
>>>['c','b','a']

Rozwiązanie nie jest tak eleganckie w porównaniu do innych, jednak w porównaniu do pand.unique (), numpy.unique () pozwala również sprawdzić, czy zagnieżdżone tablice są unikalne wzdłuż jednej wybranej osi.

 14
Author: G M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-06 10:51:24

Proste i łatwe:

myList = [1, 2, 3, 1, 2, 5, 6, 7, 8]
cleanlist = []
[cleanlist.append(x) for x in myList if x not in cleanlist]

Wyjście:

>>> cleanlist 
[1, 2, 3, 5, 6, 7, 8]
 13
Author: Nima Soroush,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-14 23:33:40

Miałem dict na swojej liście, więc nie mogłem skorzystać z powyższego podejścia. Mam błąd:

TypeError: unhashable type:

Więc jeśli zależy ci na zamów i / lub niektóre przedmioty są nieszablonowe . To może okazać się przydatne:

def make_unique(original_list):
    unique_list = []
    [unique_list.append(obj) for obj in original_list if obj not in unique_list]
    return unique_list

Niektórzy mogą uznać zrozumienie listy z efektem ubocznym za nie dobre rozwiązanie. Oto alternatywa:

def make_unique(original_list):
    unique_list = []
    map(lambda x: unique_list.append(x) if (x not in unique_list) else False, original_list)
    return unique_list
 11
Author: cchristelis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-27 10:58:38

Spróbuj użyć zestawów:

import sets
t = sets.Set(['a', 'b', 'c', 'd'])
t1 = sets.Set(['a', 'b', 'c'])

print t | t1
print t - t1
 6
Author: Charlie Martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 00:54:13

Możesz też to zrobić:

>>> t = [1, 2, 3, 3, 2, 4, 5, 6]
>>> s = [x for i, x in enumerate(t) if i == t.index(x)]
>>> s
[1, 2, 3, 4, 5, 6]

Powyższe działanie polega na tym, że metoda index zwraca tylko pierwszy indeks elementu. Zduplikowane elementy mają wyższe indeksy. Zobacz tutaj :

Lista.index (x [, start [, end]])
Zwraca indeks bazujący na 0 na liście pierwszy element, którego wartością jest x. podnosi wartość ValueError jeśli nie ma taki przedmiot.

 6
Author: Atonal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-06 09:12:26

Wszystkie podejścia zachowujące porządek, które widziałem tutaj do tej pory, albo używają naiwnego porównania (z O (N^2) w najlepszym przypadku złożoności czasowej) lub ciężkiej wagi OrderedDicts/set+list kombinacje, które są ograniczone do hashable wejść. Oto rozwiązanie niezależne od hasha O (nlogn):

Update dodano argument key, dokumentację i kompatybilność Pythona 3.

# from functools import reduce <-- add this import on Python 3

def uniq(iterable, key=lambda x: x):
    """
    Remove duplicates from an iterable. Preserves order. 
    :type iterable: Iterable[Ord => A]
    :param iterable: an iterable of objects of any orderable type
    :type key: Callable[A] -> (Ord => B)
    :param key: optional argument; by default an item (A) is discarded 
    if another item (B), such that A == B, has already been encountered and taken. 
    If you provide a key, this condition changes to key(A) == key(B); the callable 
    must return orderable objects.
    """
    # Enumerate the list to restore order lately; reduce the sorted list; restore order
    def append_unique(acc, item):
        return acc if key(acc[-1][1]) == key(item[1]) else acc.append(item) or acc 
    srt_enum = sorted(enumerate(iterable), key=lambda item: key(item[1]))
    return [item[1] for item in sorted(reduce(append_unique, srt_enum, [srt_enum[0]]))] 
 6
Author: Eli Korvigo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-12 14:59:10

Najlepszym sposobem usuwania duplikatów z listy jest użycie funkcji set () , dostępnej w Pythonie, ponownie konwertującej ten set na list

In [2]: some_list = ['a','a','v','v','v','c','c','d']
In [3]: list(set(some_list))
Out[3]: ['a', 'c', 'd', 'v']
 5
Author: Anurag Misra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-17 07:39:25

Ten dba o porządek bez większych kłopotów (OrderdDict & inne). Prawdopodobnie nie jest to najbardziej Pythoniczny sposób, ani najkrótsza droga, ale robi sztuczkę:

def remove_duplicates(list):
    ''' Removes duplicate items from a list '''
    singles_list = []
    for element in list:
        if element not in singles_list:
            singles_list.append(element)
    return singles_list
 4
Author: cgf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-02 11:37:54

Zmniejsz wariant z zachowaniem kolejności:

Załóżmy, że mamy listę:

l = [5, 6, 6, 1, 1, 2, 2, 3, 4]

Zmniejsz wariant (nieefektywny):

>>> reduce(lambda r, v: v in r and r or r + [v], l, [])
[5, 6, 1, 2, 3, 4]

5 x szybszy, ale bardziej wyrafinowany

>>> reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0]
[5, 6, 1, 2, 3, 4]

Wyjaśnienie:

default = (list(), set())
# user list to keep order
# use set to make lookup faster

def reducer(result, item):
    if item not in result[1]:
        result[0].append(item)
        result[1].add(item)
    return result

reduce(reducer, l, default)[0]
 4
Author: Sergey M Nikitin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-27 14:56:35

Poniższy kod jest prosty do usunięcia duplikatu z listy

def remove_duplicates(x):
    a = []
    for i in x:
        if i not in a:
            a.append(i)
    return a

print remove_duplicates([1,2,2,3,3,4])

Zwraca [1,2,3,4]

 4
Author: vinay hegde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-13 21:54:27

Istnieje wiele innych odpowiedzi sugerujących różne sposoby, ale wszystkie są to operacje wsadowe, a niektóre z nich odrzucają pierwotną kolejność. Może to być w porządku w zależności od tego, czego potrzebujesz, ale jeśli chcesz iterować wartości w kolejności pierwszego wystąpienia każdej wartości i chcesz usunąć duplikaty w locie, a nie wszystkie naraz, możesz użyć tego generatora:

def uniqify(iterable):
    seen = set()
    for item in iterable:
        if item not in seen:
            seen.add(item)
            yield item

To zwraca generator / iterator, więc możesz go używać wszędzie, gdzie możesz użyć iterator.

for unique_item in uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]):
    print(unique_item, end=' ')

print()

Wyjście:

1 2 3 4 5 6 7 8

Jeśli chcesz list, możesz to zrobić:

unique_list = list(uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]))

print(unique_list)

Wyjście:

[1, 2, 3, 4, 5, 6, 7, 8]
 4
Author: Cyphase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-25 23:51:57

Bez użycia zestawu

data=[1, 2, 3, 1, 2, 5, 6, 7, 8]
uni_data=[]
for dat in data:
    if dat not in uni_data:
        uni_data.append(dat)

print(uni_data) 
 4
Author: Suresh Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 10:28:17

Oto najszybsze rozwiązanie pythoniczne comaring do innych wymienionych w odpowiedziach.

Wykorzystanie szczegółów implementacji oceny zwarciowej pozwala na wykorzystanie rozumienia list, co jest wystarczająco szybkie. visited.add(item) zawsze zwraca None jako wynik, który jest oceniany jako False, więc prawa strona or zawsze byłaby wynikiem takiego wyrażenia.

Time it yourself

def deduplicate(sequence):
    visited = set()
    adder = visited.add  # get rid of qualification overhead
    out = [adder(item) or item for item in sequence if item not in visited]
    return out
 3
Author: thodnev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-01 19:56:01

Za pomocą set :

a = [0,1,2,3,4,3,3,4]
a = list(set(a))
print a

Za pomocą unique :

import numpy as np
a = [0,1,2,3,4,3,3,4]
a = np.unique(a).tolist()
print a
 3
Author: Nurul Akter Towhid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-29 00:39:14

Bardzo prosty sposób w Pythonie 3:

>>> n = [1, 2, 3, 4, 1, 1]
>>> n
[1, 2, 3, 4, 1, 1]
>>> m = sorted(list(set(n)))
>>> m
[1, 2, 3, 4]
 3
Author: Wariored,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-12 16:16:39

W dzisiejszych czasach możesz użyć klasy Counter:

>>> import collections
>>> c = collections.Counter([1, 2, 3, 4, 5, 6, 1, 1, 1, 1])
>>> c.keys()
dict_keys([1, 2, 3, 4, 5, 6])
 2
Author: jb.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-18 10:54:54

Oto przykład, zwracając listę bez powtórzeń zachowując porządek. Nie wymaga żadnego importu zewnętrznego.

def GetListWithoutRepetitions(loInput):
    # return list, consisting of elements of list/tuple loInput, without repetitions.
    # Example: GetListWithoutRepetitions([None,None,1,1,2,2,3,3,3])
    # Returns: [None, 1, 2, 3]

    if loInput==[]:
        return []

    loOutput = []

    if loInput[0] is None:
        oGroupElement=1
    else: # loInput[0]<>None
        oGroupElement=None

    for oElement in loInput:
        if oElement<>oGroupElement:
            loOutput.append(oElement)
            oGroupElement = oElement
    return loOutput
 2
Author: Apogentus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 10:33:18

Zaznacz to, jeśli chcesz usunąć duplikaty (edycja w miejscu zamiast zwracania nowej listy) bez użycia wbudowanego zestawu dict.keys, uniqify, counter

>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> for i in t:
...     if i in t[t.index(i)+1:]:
...         t.remove(i)
... 
>>> t
[3, 1, 2, 5, 6, 7, 8]
 2
Author: user2404093,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-20 15:20:40

Myślę, że konwersja do set jest najprostszym sposobem na usunięcie duplikatu:

list1 = [1,2,1]
list1 = list(set(list1))
print list1
 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-29 00:33:01

Aby usunąć duplikaty, zrób z niego zestaw, a następnie ponownie zrób z niego listę i wydrukuj/użyj go. Zestaw ma gwarancję posiadania unikalnych elementów. Na przykład:

a = [1,2,3,4,5,9,11,15]
b = [4,5,6,7,8]
c=a+b
print c
print list(set(c)) #one line for getting unique elements of c

Wynik będzie następujący (sprawdzany w Pythonie 2.7)

[1, 2, 3, 4, 5, 9, 11, 15, 4, 5, 6, 7, 8]  #simple list addition with duplicates
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15] #duplicates removed!!
 1
Author: krozaine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-25 08:38:44

Możesz to zrobić po prostu za pomocą zestawów.

Krok 1: Pobierz różne elementy list
Krok 2 Get Common elements of lists
Krok 3 połącz je

In [1]: a = ["apples", "bananas", "cucumbers"]

In [2]: b = ["pears", "apples", "watermelons"]

In [3]: set(a).symmetric_difference(b).union(set(a).intersection(b))
Out[3]: {'apples', 'bananas', 'cucumbers', 'pears', 'watermelons'}
 1
Author: Anurag Misra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 11:11:54
def remove_duplicates(A):
   [A.pop(count) for count,elem in enumerate(A) if A.count(elem)!=1]
   return A

Lista do usuwania duplikatów

 1
Author: ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-26 23:23:42