Programing

두 목록 간의 공통 요소 비교

lottogame 2020. 8. 12. 22:08
반응형

두 목록 간의 공통 요소 비교


def common_elements(list1, list2):
    """
    Return a list containing the elements which are in both list1 and list2

    >>> common_elements([1,2,3,4,5,6], [3,5,7,9])
    [3, 5]
    >>> common_elements(['this','this','n','that'],['this','not','that','that'])
    ['this', 'that']
    """
    for element in list1:
        if element in list2:
            return list(element)

지금까지 확인했지만 작동하지 않는 것 같습니다!

어떤 아이디어?


>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

집합을 사용하고 한 줄로 공통점을 얻을 수도 있습니다. 집합 중 하나에서 차이점을 포함하는 집합을 뺍니다.

A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))

제안한 솔루션 S.MarkSilentGhost는 그것이 파이썬 방식으로 수행하는 방법을 일반적으로 말해,하지만 난 당신의 솔루션은 작업을하지 않는 이유를 알고부터 당신은 또한 혜택을 누릴 수있다 생각했다. 문제는 두 목록에서 첫 번째 공통 요소를 찾으면 해당 단일 요소 만 반환한다는 것입니다. result목록 을 만들고 해당 목록에서 공통 요소를 수집하여 솔루션을 수정할 수 있습니다 .

def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return result

목록 내포를 사용하는 더 짧은 버전 :

def common_elements(list1, list2):
    return [element for element in list1 if element in list2]

그러나 내가 말했듯이 이것은 이것을 수행하는 매우 비효율적 인 방법입니다. Python의 내장 세트 유형은 내부적으로 C로 구현되기 때문에 훨씬 더 효율적입니다.


set 교차점 사용, set (list1) & set (list2)

>>> def common_elements(list1, list2):
...     return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>

결과 목록은 원래 목록과 순서가 다를 수 있습니다.


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

x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]

이전 답변은 모두 고유 한 공통 요소를 찾기 위해 작동하지만 목록에서 반복되는 항목을 설명하지 못합니다. 공통 요소가 목록에서 공통적으로 발견되는 것과 동일한 번호로 표시되도록하려면 다음 한 줄을 사용할 수 있습니다.

l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]

or True당신이 평가하는 모든 요소를 기대한다면 부분에만 필요합니다 False.


이것은 for 루프보다 세트가 더 쉽다고 생각하는 내 제안입니다.

def unique_common_items(list1, list2):
   # Produce the set of *unique* common items in two lists.
   return list(set(list1) & set(list2))

세트는이 문제를 해결할 수있는 또 다른 방법입니다.

a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}

1) Method1 saving list1 is dictionary and then iterating each elem in list2

def findarrayhash(a,b):
    h1={k:1 for k in a}
    for val in b:
        if val in h1:
            print("common found",val)
            del h1[val]
        else:
            print("different found",val)
    for key in h1.iterkeys():
        print ("different found",key)

Finding Common and Different elements:

2) Method2 using set

def findarrayset(a,b):
    common = set(a)&set(b)
    diff=set(a)^set(b)
    print list(common)
    print list(diff) 

Use a generator:

common = (x for x in list1 if x in list2)

The advantage here is that this will return in constant time (nearly instant) even when using huge lists or other huge iterables.

For example,

list1 =  list(range(0,10000000))
list2=list(range(1000,20000000))
common = (x for x in list1 if x in list2)

All other answers here will take a very long time with these values for list1 and list2.

You can then iterate the answer with

for i in common: print(i)

Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.

The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't give the correct number of elements when the input order matters.

#finds common elements
def common(list1, list2):
    result = []
    intersect = list(set(list1).intersection(list2))

    #using the intersection, find the min
    count1 = 0
    count2 = 0
    for i in intersect: 
        for j in list1:
            if i == j:
                count1 += 1
        for k in list2: 
            if i == k:
                count2 += 1
        minCount = min(count2,count1)
        count1 = 0
        count2 = 0

        #append common factor that many times
        for j in range(minCount):
            result.append(i)

    return result

f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=[]

for i in f_list:
    # checking if each element of first list exists in second list
    if i in s_list:
        #if so add it in common elements list
        common_elements.append(i) 
print(common_elements)

a_list = range(1,10)
b_list = range(5, 25)
both = []

for i in b_list:
    for j in a_list:
        if i == j:
            both.append(i)

Hi, this is my propose (very simple)

import random

i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i: 
    if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
        print(x) # print out the results

def common_member(a, b): 
    a_set = set(a) 
    b_set = set(b) 
    if (a_set & b_set): 
        print(a_set & b_set) 
    else: 
        print("No common elements") 

list_1=range(0,100)
list_2=range(0,100,5)
final_list=[]
for i in list_1:
    for j in list_2:
        if i==j:
            final_list.append(i)
print(set(final_list))

Your problem is that you're returning from inside the for loop so you'll only get the first match. The solution is to move your return outside the loop.

def elementosEnComunEntre(lista1,lista2):

    elementosEnComun = set()

    for e1 in lista1:
         if(e1 in lista2):
             elementosEnComun.add(e1)

    return list(elementosEnComun)

def list_common_elements(l_1,l_2,_unique=1,diff=0):
    if not diff:
        if _unique:
            return list(set(l_1)&set(l_2))
        if not _unique:
            return list((i for i in l_1 if i in l_2))
    if diff:
        if _unique:
            return list(set(l_1)^set(l_2))
        if not _unique:
            return list((i for i in l_1 if i not in l_2))
"""
Example:
l_1=             [0, 1, 2, 3, 3, 4, 5]
l_2=             [6, 7, 8, 8, 9, 5, 4, 3, 2]
look for diff
l_2,l_1,diff=1,_unique=1: [0, 1, 6, 7, 8, 9]        sorted(unique(L_2 not in L_1) + unique(L_1 not in L_2))
l_2,l_1,diff=1,_unique=0: [6, 7, 8, 8, 9]           L_2 not in L_1
l_1,l_2,diff=1,_unique=1: [0, 1, 6, 7, 8, 9]        sorted(unique(L_1 not in L_2) + unique(L_2 not in L_1))
l_1,l_2,diff=1,_unique=0: [0, 1]                    L_1 not in L_2
look for same
l_2,l_1,diff=0,_unique=1: [2, 3, 4, 5]              unique(L2 in L1)
l_2,l_1,diff=0,_unique=0: [5, 4, 3, 2]              L2 in L1
l_1,l_2,diff=0,_unique=1: [2, 3, 4, 5]              unique(L1 in L2)
l_1,l_2,diff=0,_unique=0: [2, 3, 3, 4, 5]           L1 in L2
"""

This function provides the ability to compare two lists (L_1 vs. L_2). DIFF parameter set the comparison to search for common elements (DIFF==True) or different elements (DIFF==False) between both lists. On the next level the behavior of the method is set by _UNIQUE parameter. _UNIQUE==True will use Python sets – in this case the method returns a sorted list of unique elements satisfying DIFF. When _UNIQUE==False – the returned list is more explicit, i.e. it will first contain all elements of L_1 followed by all elements of L_2 satisfying the DIFF. Since the output will contain repetitive occurrences of elements in L_1 and L_2 satisfying DIFF, the user could post-count the number of times an element differs or is common between the lists. As this proposal is simply a compilation of code proposed by “cowlinator” and J.S Method2, pleases see these authors posts for discussion on the speed and the performance of the calculation. Credits cowlinator and J.S. Method2


list1=[1,2,3,4,5]
list2=[4,5,6,3,7]
for c in list1: 
    if(c in list2): 
        print("common elements in list are:",c)
    else:
        print("non common elements in list are:",c)

참고URL : https://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists

반응형