Znaleźć skrzyżowanie dwóch zagnieżdżonych list?
Wiem jak uzyskać przecięcie dwóch płaskich list:
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
Lub
def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
Ale kiedy muszę znaleźć skrzyżowanie dla zagnieżdżonych list, wtedy zaczynają się moje problemy:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
Na koniec chciałbym otrzymać:
c3 = [[13,32],[7,13,28],[1,6]]
Możecie mi pomóc?
Powiązane
20 answers
Jeśli chcesz:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]
Oto twoje rozwiązanie dla Pythona 2:
c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]
W Pythonie 3 filter
zwraca iterable zamiast list
, więc musisz zawinąć filter
wywołania z list()
:
c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]
Explanation:
Część filtra pobiera każdą pozycję sublisty i sprawdza, czy znajduje się ona na liście źródłowej c1. Zrozumienie listy jest wykonywane dla każdej sublisty w c2.
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-05-29 05:00:30
Nie musisz definiować przecięcia. To już pierwsza klasa.
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])
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 20:56:49
Dla osób szukających przecięcia dwóch list, Asker podał dwie metody:
b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2]
I
def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2)
Ale istnieje metoda hybrydowa, która jest bardziej efektywna, ponieważ musisz wykonać tylko jedną konwersję między listą/zestawem, w przeciwieństwie do trzech:
b1 = [1,2,3,4,5]
b2 = [3,4,5,6]
s2 = set(b2)
b3 = [val for val in b1 if val in s2]
TO BĘDZIE DZIAŁAĆ W O(n), podczas gdy jego oryginalna metoda polegająca na zrozumieniu listy będzie działać w O (N^2)
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
2009-12-09 17:26:06
Podejście funkcjonalne:
input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]
result = reduce(set.intersection, map(set, input_list))
I może być stosowany do bardziej ogólnego przypadku List 1 +
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-09-26 10:43:21
Pure list comprehension version
>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> c1set = frozenset(c1)
Wariant spłaszczenia:
>>> [n for lst in c2 for n in lst if n in c1set]
[13, 32, 7, 13, 28, 1, 6]
Wariant zagnieżdżony:
>>> [[n for n in lst if n in c1set] for lst in c2]
[[13, 32], [7, 13, 28], [1, 6]]
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
2009-03-13 14:35:58
Operator & przyjmuje przecięcie dwóch zbiorów.
{1, 2, 3} & {2, 3, 4}
Out[1]: {2, 3}
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
2019-11-18 16:33:58
Pythoniczny sposób na przecięcie 2 List to:
[x for x in list1 if x in list2]
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-09-24 18:27:39
Powinieneś spłaszczyć używając tego kodu ( zaczerpniętego z http://kogs-www.informatik.uni-hamburg.de/ ~ meine / python_tricks ), kod jest niesprawdzony, ale jestem pewien, że działa:
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
result = []
for el in x:
#if isinstance(el, (list, tuple)):
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
Po spłaszczeniu listy wykonujesz przecięcie w zwykły sposób:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
def intersect(a, b):
return list(set(a) & set(b))
print intersect(flatten(c1), flatten(c2))
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
2009-03-13 13:53:16
Ponieważ intersect
zostało zdefiniowane, wystarczy podstawowe zrozumienie listy:
>>> c3 = [intersect(c1, i) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]
Poprawa dzięki uwagom S. Lotta i TM."przypisana Uwaga": {]}
>>> c3 = [list(set(c1).intersection(i)) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]
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
2012-02-21 11:38:00
Podane:
> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
Uważam, że poniższy kod działa dobrze i może bardziej zwięzły, jeśli używasz operacji set:
> c3 = [list(set(f)&set(c1)) for f in c2]
Dostał:
> [[32, 13], [28, 13, 7], [1, 6]]
Jeśli potrzebne jest zamówienie:
> c3 = [sorted(list(set(f)&set(c1))) for f in c2]
Mamy:
> [[13, 32], [7, 13, 28], [1, 6]]
Przy okazji, dla bardziej pythonowego stylu, Ten też jest w porządku:
> c3 = [ [i for i in set(f) if i in c1] for f in c2]
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-11-03 02:32:44
Nie wiem, czy jestem spóźniony w odpowiedzi na twoje pytanie. Po przeczytaniu Twojego pytania wymyśliłem funkcję intersect (), która może działać zarówno na liście, jak i na zagnieżdżonej liście. Użyłem rekurencji do zdefiniowania tej funkcji, jest ona bardzo intuicyjna. Mam nadzieję, że to jest to, czego szukasz:
def intersect(a, b):
result=[]
for i in b:
if isinstance(i,list):
result.append(intersect(a,i))
else:
if i in a:
result.append(i)
return result
Przykład:
>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> print intersect(c1,c2)
[[13, 32], [7, 13, 28], [1, 6]]
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> print intersect(b1,b2)
[4, 5]
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-02-09 16:26:44
Czy uważasz, że [1,2]
przecinają się z [1, [2]]
? To znaczy, czy chodzi tylko o liczby, na których Ci zależy, czy też o strukturę listy?
Jeśli tylko liczby, zbadaj, jak "spłaścić" listy, a następnie użyj metody set()
.
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
2009-03-13 13:45:14
Ja też szukałem sposobu, żeby to zrobić, i ostatecznie skończyło się tak:
def compareLists(a,b):
removed = [x for x in a if x not in b]
added = [x for x in b if x not in a]
overlap = [x for x in a if x in b]
return [removed,added,overlap]
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-11-29 14:40:50
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(c2[i]).intersection(set(c1))) for i in xrange(len(c2))]
c3
->[[32, 13], [28, 13, 7], [1, 6]]
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-11-21 09:35:08
Możemy użyć do tego metody set:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
result = []
for li in c2:
res = set(li) & set(c1)
result.append(list(res))
print result
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-05-05 12:29:40
Aby zdefiniować przecięcie, które poprawnie uwzględnia Kardynalność elementów użyj Counter
:
from collections import Counter
>>> c1 = [1, 2, 2, 3, 4, 4, 4]
>>> c2 = [1, 2, 4, 4, 4, 4, 5]
>>> list((Counter(c1) & Counter(c2)).elements())
[1, 2, 4, 4, 4]
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-05-18 06:39:17
# Problem: Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?
Oto jeden sposób, aby ustawić c3
, który nie obejmuje zestawów:
c3 = []
for sublist in c2:
c3.append([val for val in c1 if val in sublist])
Ale jeśli wolisz używać tylko jednej linii, możesz to zrobić:
c3 = [[val for val in c1 if val in sublist] for sublist in c2]
To rozumienie listy wewnątrz rozumienia listy, co jest trochę nietypowe, ale myślę, że nie powinieneś mieć zbyt wiele problemów z jego śledzeniem.
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-24 20:19:39
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(i) & set(c1)) for i in c2]
c3
[[32, 13], [28, 13, 7], [1, 6]]
Dla mnie to bardzo elegancki i szybki sposób na to :)
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-05-21 09:47:02
Płaska lista może być wykonana przez reduce
łatwo.
All you need to use initializer - trzeci argument w funkcji reduce
.
reduce(
lambda result, _list: result.append(
list(set(_list)&set(c1))
) or result,
c2,
[])
Powyższy kod działa zarówno dla python2 jak i python3, ale musisz zaimportować moduł reduce jako from functools import reduce
. Zobacz poniższy link, aby uzyskać szczegółowe informacje.
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
2019-07-01 22:25:06
Prosty sposób na znalezienie różnicy i przecięcia pomiędzy iterabami
Użyj tej metody, jeśli powtarzanie ma znaczenie
from collections import Counter
def intersection(a, b):
"""
Find the intersection of two iterables
>>> intersection((1,2,3), (2,3,4))
(2, 3)
>>> intersection((1,2,3,3), (2,3,3,4))
(2, 3, 3)
>>> intersection((1,2,3,3), (2,3,4,4))
(2, 3)
>>> intersection((1,2,3,3), (2,3,4,4))
(2, 3)
"""
return tuple(n for n, count in (Counter(a) & Counter(b)).items() for _ in range(count))
def difference(a, b):
"""
Find the symmetric difference of two iterables
>>> difference((1,2,3), (2,3,4))
(1, 4)
>>> difference((1,2,3,3), (2,3,4))
(1, 3, 4)
>>> difference((1,2,3,3), (2,3,4,4))
(1, 3, 4, 4)
"""
diff = lambda x, y: tuple(n for n, count in (Counter(x) - Counter(y)).items() for _ in range(count))
return diff(a, b) + diff(b, a)
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
2020-03-21 06:14:40