두 목록 간의 공통 요소 비교 ‘that’]

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]

그러나 내가 말했듯이 이것은 매우 비효율적 인 방법입니다. 파이썬의 내장 세트 유형은 내부적으로 C로 구현 될 때보 다 효율적입니다.


답변

집합 교차점 사용, 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]


답변

세트는 우리가 이것을 해결할 수있는 또 다른 방법입니다

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


답변

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

나는 이것을 해결할 수있는 3 가지 방법을 알고 있습니다. 물론 더있을 수 있습니다.

1-

common_elements = [e for e in list1 if e in list2]

2-

import numpy as np
common_elements = np.intersect1d(list1, list2)

삼-

common_elements = set(list1).intersection(list2)

세트가 해시 테이블을 사용하여 구현되므로 세 번째 방법이 가장 빠릅니다.