두 Python 리스트에서 공통 요소 찾는 방법

PythonBeginner
지금 연습하기

소개

Python 리스트는 데이터를 저장하고 구성할 수 있는 기본적인 데이터 구조입니다. 두 리스트 간의 공통 요소를 찾는 것은 데이터 분석에서 웹 애플리케이션 구축에 이르기까지 많은 프로그래밍 시나리오에서 유용한 실용적인 기술입니다. 이 실습 랩에서는 Python 리스트 간의 공유 요소를 식별하고 각 접근 방식을 언제 사용해야 하는지 이해하는 여러 가지 기술을 배우게 됩니다.

이 튜토리얼이 끝나면 리스트 조작을 위한 Python 의 내장 함수와 메서드를 실질적으로 경험하게 되며, 이러한 기술을 자신의 프로젝트에 구현할 수 있게 됩니다.

Python 리스트 생성 및 이해

몇 가지 Python 리스트를 생성하고 기본 연산을 탐색하는 것으로 시작해 보겠습니다. 이렇게 하면 공통 요소를 찾기 전에 필요한 기반을 갖추게 됩니다.

Python 리스트란 무엇인가요?

Python 에서 리스트는 서로 다른 데이터 유형의 요소를 저장할 수 있는 항목의 정렬된 컬렉션입니다. 리스트는 쉼표로 구분된 항목과 함께 대괄호 []를 사용하여 생성됩니다.

첫 번째 Python 파일을 만들고 리스트를 탐색해 보겠습니다.

  1. WebIDE 를 열고 "File" > "New File"을 클릭하여 새 파일을 만듭니다.
  2. 파일을 /home/labex/project 디렉토리에 list_basics.py로 저장합니다.
  3. 파일에 다음 코드를 추가합니다.
## Creating basic lists
fruits = ["apple", "banana", "cherry", "orange", "kiwi"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

## Printing the lists
print("Fruits list:", fruits)
print("Numbers list:", numbers)
print("Mixed list:", mixed)

## Accessing list elements using index
print("\nAccessing list elements:")
print("First fruit:", fruits[0])
print("Last number:", numbers[-1])

## Slicing lists
print("\nSlicing lists:")
print("First three fruits:", fruits[0:3])
print("Last two numbers:", numbers[-2:])

## List operations
print("\nList operations:")
print("Length of fruits list:", len(fruits))
fruits.append("mango")
print("After adding mango:", fruits)
fruits.remove("banana")
print("After removing banana:", fruits)

## Checking if an element exists in a list
print("\nChecking if elements exist:")
print("Is 'apple' in fruits?", "apple" in fruits)
print("Is 'grape' in fruits?", "grape" in fruits)
  1. 터미널을 열고 다음을 입력하여 파일을 실행합니다.
cd ~/project
python3 list_basics.py

수행한 다양한 리스트 연산을 보여주는 출력이 표시됩니다.

Fruits list: ['apple', 'banana', 'cherry', 'orange', 'kiwi']
Numbers list: [1, 2, 3, 4, 5]
Mixed list: [1, 'hello', 3.14, True]

Accessing list elements:
First fruit: apple
Last number: 5

Slicing lists:
First three fruits: ['apple', 'banana', 'cherry']
Last two numbers: [4, 5]

List operations:
Length of fruits list: 5
After adding mango: ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'mango']
After removing banana: ['apple', 'cherry', 'orange', 'kiwi', 'mango']

Checking if elements exist:
Is 'apple' in fruits? True
Is 'grape' in fruits? False

이제 Python 리스트의 기본 사항을 이해했으므로 두 리스트 간의 공통 요소를 찾을 준비가 되었습니다. 다음 단계에서 사용할 두 개의 샘플 리스트를 만들어 보겠습니다.

  1. 다음 내용으로 common_elements_data.py라는 새 파일을 만듭니다.
## Create two lists with some common elements
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8, 9]

print("List 1:", list1)
print("List 2:", list2)
print("We'll find the common elements between these lists in the next steps.")
  1. 이 파일을 실행합니다.
python3 common_elements_data.py

그러면 다음 단계에서 공통 요소를 찾는 데 사용할 두 개의 리스트가 표시됩니다.

List 1: [1, 2, 3, 4, 5, 6]
List 2: [4, 5, 6, 7, 8, 9]
We'll find the common elements between these lists in the next steps.

Python 리스트를 성공적으로 생성하고 탐색했습니다. 다음 단계에서는 이 두 리스트 간의 공통 요소를 찾는 방법을 배우겠습니다.

다양한 방법을 사용하여 공통 요소 찾기

이제 두 개의 리스트가 있으므로, 두 리스트 간의 공통 요소를 찾는 여러 가지 방법을 살펴보겠습니다. 각 방법에는 장점이 있으며, 모든 방법을 이해하면 특정 요구 사항에 맞는 올바른 접근 방식을 선택하는 데 도움이 됩니다.

방법 1: 루프 방법 사용

가장 간단한 방법은 루프와 in 연산자를 사용하여 한 리스트의 각 요소가 다른 리스트에도 있는지 확인하는 것입니다.

  1. 다음 내용으로 common_loop.py라는 새 파일을 만듭니다.
## Import our lists from the previous file
from common_elements_data import list1, list2

## Find common elements using a loop
common_elements = []
for item in list1:
    if item in list2:
        common_elements.append(item)

print("Common elements using loop method:", common_elements)
  1. 스크립트를 실행합니다.
python3 common_loop.py

다음과 같은 출력이 표시됩니다.

Common elements using loop method: [4, 5, 6]

이 방법은 이해하기 쉽지만, in 연산자가 첫 번째 리스트의 각 요소에 대해 전체 두 번째 리스트를 검색해야 하므로 큰 리스트의 경우 비효율적일 수 있습니다.

방법 2: 집합 (Sets) 사용

더 효율적인 방법은 멤버십 테스트 및 공통 요소 찾기에 최적화된 Python 의 set 데이터 구조를 활용하는 것입니다.

  1. 다음 내용으로 common_sets.py라는 새 파일을 만듭니다.
## Import our lists from the previous file
from common_elements_data import list1, list2

## Convert lists to sets and find intersection
set1 = set(list1)
set2 = set(list2)
common_elements = list(set1.intersection(set2))  ## Alternative: list(set1 & set2)

print("Common elements using set intersection:", common_elements)
  1. 스크립트를 실행합니다.
python3 common_sets.py

다음과 같은 출력이 표시됩니다.

Common elements using set intersection: [4, 5, 6]

집합 방법은 일반적으로 루프 방법보다 훨씬 빠르며, 특히 큰 리스트의 경우 더욱 그렇습니다. 그러나 집합은 요소의 원래 순서를 유지하지 않는다는 점에 유의하십시오.

방법 3: 리스트 컴프리헨션 (List Comprehension) 사용

리스트 컴프리헨션은 기존 리스트를 기반으로 리스트를 만드는 간결한 방법을 제공합니다. 이를 사용하여 한 줄의 코드에서 공통 요소를 찾을 수 있습니다.

  1. 다음 내용으로 common_comprehension.py라는 새 파일을 만듭니다.
## Import our lists from the previous file
from common_elements_data import list1, list2

## Find common elements using list comprehension
common_elements = [item for item in list1 if item in list2]

print("Common elements using list comprehension:", common_elements)
  1. 스크립트를 실행합니다.
python3 common_comprehension.py

다음과 같은 출력이 표시됩니다.

Common elements using list comprehension: [4, 5, 6]

리스트 컴프리헨션은 루프 방법보다 간결하며 요소의 순서를 유지하지만, 루프 방법과 동일한 성능 특성을 갖습니다.

모든 방법 비교

세 가지 방법을 모두 비교하는 파일을 만들어 보겠습니다.

  1. 다음 내용으로 compare_methods.py라는 새 파일을 만듭니다.
## Import our lists from the previous file
from common_elements_data import list1, list2

## Method 1: Using a loop
common_loop = []
for item in list1:
    if item in list2:
        common_loop.append(item)

## Method 2: Using sets
common_sets = list(set(list1) & set(list2))

## Method 3: Using list comprehension
common_comprehension = [item for item in list1 if item in list2]

## Print results from all methods
print("Original lists:")
print("List 1:", list1)
print("List 2:", list2)
print("\nCommon elements using different methods:")
print("Loop method:", common_loop)
print("Set method:", common_sets)
print("List comprehension:", common_comprehension)
  1. 스크립트를 실행합니다.
python3 compare_methods.py

다음과 같은 출력이 표시됩니다.

Original lists:
List 1: [1, 2, 3, 4, 5, 6]
List 2: [4, 5, 6, 7, 8, 9]

Common elements using different methods:
Loop method: [4, 5, 6]
Set method: [4, 5, 6]
List comprehension: [4, 5, 6]

세 가지 방법 모두 동일한 결과를 제공합니다. list1list2 간의 공통 요소는 [4, 5, 6]입니다.

이제 Python 에서 두 리스트 간의 공통 요소를 찾는 세 가지 다른 방법을 배웠습니다. 다음 단계에서는 이러한 기술의 몇 가지 실용적인 응용 프로그램을 살펴보겠습니다.

공통 요소 찾기의 실용적인 응용

리스트 간의 공통 요소를 찾는 것이 유용한 실제 응용 프로그램을 살펴보겠습니다. 이전 단계에서 배운 방법을 사용하여 이러한 예제를 구현합니다.

응용 1: 공통 관심사 찾기

공통 관심사를 공유하는 사용자를 표시하려는 소셜 네트워킹 애플리케이션을 구축한다고 상상해 보세요. 이 시나리오를 시뮬레이션해 보겠습니다.

  1. 다음 내용으로 common_interests.py라는 새 파일을 만듭니다.
## User interests data
user1_interests = ["programming", "music", "movies", "hiking", "cooking"]
user2_interests = ["music", "photography", "travel", "cooking", "gaming"]

print("User 1's interests:", user1_interests)
print("User 2's interests:", user2_interests)

## Find common interests using the set method (most efficient)
common_interests = list(set(user1_interests) & set(user2_interests))

print("\nCommon interests:", common_interests)
print("Number of common interests:", len(common_interests))

## Generate a friendly message based on common interests
if len(common_interests) > 0:
    message = f"You and this user both enjoy {' and '.join(common_interests)}!"
    print("\nSuggested connection message:")
    print(message)
else:
    print("\nNo common interests found.")
  1. 스크립트를 실행합니다.
python3 common_interests.py

다음과 같은 출력이 표시됩니다.

User 1's interests: ['programming', 'music', 'movies', 'hiking', 'cooking']
User 2's interests: ['music', 'photography', 'travel', 'cooking', 'gaming']

Common interests: ['music', 'cooking']
Number of common interests: 2

Suggested connection message:
You and this user both enjoy music and cooking!

이 예제는 공통 요소를 찾는 것이 애플리케이션에서 개인화된 사용자 경험을 만드는 데 어떻게 도움이 되는지 보여줍니다.

응용 2: 쇼핑 목록 비교

두 룸메이트가 쇼핑 목록을 가지고 있고 누가 무엇을 살지 조정하려는 시나리오를 상상해 보겠습니다. 그들은 두 목록 모두에 나타나는 항목을 식별하여 누가 해당 항목을 구매할지 결정하려고 합니다.

  1. 다음 내용으로 shopping_lists.py라는 새 파일을 만듭니다.
## Shopping lists for two roommates
roommate1_list = ["milk", "eggs", "bread", "apples", "coffee", "chicken"]
roommate2_list = ["bananas", "coffee", "cereal", "eggs", "sugar", "bread"]

print("Roommate 1's shopping list:", roommate1_list)
print("Roommate 2's shopping list:", roommate2_list)

## Find duplicate items (appears in both lists)
duplicate_items = [item for item in roommate1_list if item in roommate2_list]

## Find unique items for each roommate
roommate1_unique = [item for item in roommate1_list if item not in roommate2_list]
roommate2_unique = [item for item in roommate2_list if item not in roommate1_list]

print("\nDuplicate items (both roommates planned to buy):", duplicate_items)
print("Unique items for Roommate 1:", roommate1_unique)
print("Unique items for Roommate 2:", roommate2_unique)

## Create a combined shopping list with no duplicates
combined_list = list(set(roommate1_list) | set(roommate2_list))
print("\nCombined shopping list (no duplicates):", combined_list)

## Calculate some statistics
total_items = len(combined_list)
duplicate_count = len(duplicate_items)
efficiency = (duplicate_count / total_items) * 100

print(f"\nShopping efficiency: By coordinating, you've reduced {duplicate_count} duplicate items out of {total_items} total items.")
print(f"This saved {efficiency:.1f}% of total shopping effort!")
  1. 스크립트를 실행합니다.
python3 shopping_lists.py

다음과 같은 출력이 표시됩니다.

Roommate 1's shopping list: ['milk', 'eggs', 'bread', 'apples', 'coffee', 'chicken']
Roommate 2's shopping list: ['bananas', 'coffee', 'cereal', 'eggs', 'sugar', 'bread']

Duplicate items (both roommates planned to buy): ['eggs', 'bread', 'coffee']
Unique items for Roommate 1: ['milk', 'apples', 'chicken']
Unique items for Roommate 2: ['bananas', 'cereal', 'sugar']

Combined shopping list (no duplicates): ['chicken', 'eggs', 'coffee', 'milk', 'bananas', 'cereal', 'bread', 'sugar', 'apples']

Shopping efficiency: By coordinating, you've reduced 3 duplicate items out of 9 total items.
This saved 33.3% of total shopping effort!

응용 3: 학생 수강 신청 분석

다양한 학생의 수강 신청을 분석하는 더 복잡한 예제를 만들어 보겠습니다.

  1. 다음 내용으로 course_analysis.py라는 새 파일을 만듭니다.
## Course enrollments for different students
student_courses = {
    "Alice": ["Math101", "Physics101", "ComputerScience101", "History101"],
    "Bob": ["Math101", "Chemistry101", "Biology101", "ComputerScience101"],
    "Charlie": ["Physics101", "ComputerScience101", "English101"],
    "Diana": ["Art101", "History101", "Philosophy101", "English101"]
}

## Print all student enrollments
print("Student Enrollments:")
for student, courses in student_courses.items():
    print(f"{student}: {courses}")

print("\n--- Course Analysis ---")

## Find courses that Alice and Bob have in common
alice_bob_common = list(set(student_courses["Alice"]) & set(student_courses["Bob"]))
print(f"\nCourses Alice and Bob have in common: {alice_bob_common}")

## Find a course that all students are taking (if any)
all_students_common = set(student_courses["Alice"])
for student in student_courses:
    all_students_common &= set(student_courses[student])

if all_students_common:
    print(f"All students are taking: {list(all_students_common)}")
else:
    print("There are no courses that all students are taking.")

## Find the most popular course(s)
all_courses = []
for courses in student_courses.values():
    all_courses.extend(courses)

course_counts = {}
for course in all_courses:
    if course in course_counts:
        course_counts[course] += 1
    else:
        course_counts[course] = 1

max_count = max(course_counts.values())
most_popular = [course for course, count in course_counts.items() if count == max_count]

print(f"\nMost popular course(s) with {max_count} students: {most_popular}")

## Find which students share the most courses with each other
max_common = 0
most_common_pair = ()

students = list(student_courses.keys())
for i in range(len(students)):
    for j in range(i+1, len(students)):
        student1 = students[i]
        student2 = students[j]
        common_courses = set(student_courses[student1]) & set(student_courses[student2])
        if len(common_courses) > max_common:
            max_common = len(common_courses)
            most_common_pair = (student1, student2)
            shared_courses = common_courses

print(f"\nStudents sharing the most courses: {most_common_pair[0]} and {most_common_pair[1]}")
print(f"They share {max_common} courses: {list(shared_courses)}")
  1. 스크립트를 실행합니다.
python3 course_analysis.py

학생 간의 공통 과정 및 가장 인기 있는 과정을 포함한 과정 분석을 보여주는 출력이 표시됩니다.

이러한 예제는 공통 요소를 찾는 방법을 사용하여 다양한 실제 문제를 해결하는 방법을 보여줍니다. 서로 다른 리스트에서 중복 항목을 식별하는 기능은 데이터 분석 및 사용자 중심 애플리케이션을 만드는 강력한 기술입니다.

성능 비교 및 모범 사례

이제 공통 요소를 찾는 다양한 방법을 이해하고 실제 응용 프로그램을 살펴보았으므로, 이러한 방법의 성능을 비교하고 몇 가지 모범 사례를 설정해 보겠습니다.

성능 측정

공통 요소를 찾는 다양한 방법의 성능을 측정하는 스크립트를 만들어 보겠습니다.

  1. 다음 내용으로 performance_test.py라는 새 파일을 만듭니다.
import time
import random

def measure_time(func, *args):
    """Measure the execution time of a function"""
    start_time = time.time()
    result = func(*args)
    end_time = time.time()
    return result, end_time - start_time

## Create large test lists with some overlap
def create_test_lists(size, overlap_percent):
    """Create two lists of the given size with specified overlap percentage"""
    overlap_size = int(size * overlap_percent / 100)

    ## Create list1 with random numbers
    list1 = random.sample(range(1, size * 10), size)

    ## Create list2 with some elements from list1 (overlap) and some new elements
    overlap_elements = random.sample(list1, overlap_size)
    remaining_size = size - overlap_size
    new_elements = random.sample([x for x in range(1, size * 10) if x not in list1], remaining_size)

    list2 = overlap_elements + new_elements
    random.shuffle(list2)

    return list1, list2

## Methods to find common elements
def using_loop(list1, list2):
    common = []
    for item in list1:
        if item in list2:
            common.append(item)
    return common

def using_sets(list1, list2):
    return list(set(list1) & set(list2))

def using_comprehension(list1, list2):
    return [item for item in list1 if item in list2]

## Test with different list sizes
sizes = [100, 1000, 10000]
overlap = 50  ## 50% overlap

print("Performance comparison for finding common elements:")
print("-" * 60)
print(f"{'Size':<10}{'Loop (s)':<15}{'Set (s)':<15}{'Comprehension (s)':<20}")
print("-" * 60)

for size in sizes:
    list1, list2 = create_test_lists(size, overlap)

    ## Measure time for each method
    _, loop_time = measure_time(using_loop, list1, list2)
    _, set_time = measure_time(using_sets, list1, list2)
    _, comp_time = measure_time(using_comprehension, list1, list2)

    print(f"{size:<10}{loop_time:<15.6f}{set_time:<15.6f}{comp_time:<20.6f}")
  1. 스크립트를 실행합니다.
python3 performance_test.py

세 가지 방법 간의 성능 비교가 표시되며, 다양한 리스트 크기에 대한 실행 시간이 표시됩니다. 출력은 다음과 유사합니다 (실제 시간은 다를 수 있음).

Performance comparison for finding common elements:
------------------------------------------------------------
Size      Loop (s)       Set (s)        Comprehension (s)
------------------------------------------------------------
100       0.000134       0.000050       0.000117
1000      0.008561       0.000247       0.009018
10000     0.910376       0.001944       0.915267

모범 사례

배운 내용을 바탕으로 Python 리스트에서 공통 요소를 찾는 모범 사례가 포함된 파일을 만들어 보겠습니다.

  1. 다음 내용으로 best_practices.py라는 새 파일을 만듭니다.
"""
Best Practices for Finding Common Elements in Python Lists

This file demonstrates recommended approaches for different scenarios
when finding common elements between lists.
"""

## Sample lists for demonstration
small_list1 = [1, 2, 3, 4, 5]
small_list2 = [4, 5, 6, 7, 8]

large_list1 = list(range(1, 10001))
large_list2 = list(range(5001, 15001))

print("Best Practices for Finding Common Elements in Python Lists")
print("=" * 60)

print("\n1. For small lists (less than ~100 elements):")
print("   Any method works well, but set intersection is still recommended for clarity:")
common_small = list(set(small_list1) & set(small_list2))
print(f"   Common elements: {common_small}")

print("\n2. For large lists (100+ elements):")
print("   Always use set intersection for performance:")
## Using set method for large lists
start_time = __import__('time').time()
common_large = list(set(large_list1) & set(large_list2))
end_time = __import__('time').time()
print(f"   Found {len(common_large)} common elements in {end_time - start_time:.6f} seconds")

print("\n3. When order matters:")
print("   Use list comprehension with a set for lookup efficiency:")
lookup_set = set(small_list2)  ## Convert the second list to a set for O(1) lookups
ordered_common = [item for item in small_list1 if item in lookup_set]
print(f"   Common elements (preserving order from list1): {ordered_common}")

print("\n4. When dealing with duplicates:")
print("   Standard set intersection removes duplicates. If you need to keep them:")
list1_with_duplicates = [1, 2, 2, 3, 4, 4, 5]
list2_with_duplicates = [2, 2, 4, 5, 5, 6]
print(f"   List 1 with duplicates: {list1_with_duplicates}")
print(f"   List 2 with duplicates: {list2_with_duplicates}")

## Method that preserves duplicates
def find_common_with_duplicates(list1, list2):
    result = []
    list2_copy = list2.copy()  ## Create a copy to modify

    for item in list1:
        if item in list2_copy:
            result.append(item)
            list2_copy.remove(item)  ## Remove to avoid matching the same item again

    return result

common_with_duplicates = find_common_with_duplicates(list1_with_duplicates, list2_with_duplicates)
print(f"   Common elements (preserving duplicates): {common_with_duplicates}")

print("\nSummary:")
print("1. For most cases: Use set intersection -> list(set(list1) & set(list2))")
print("2. When order matters: Convert smaller list to set, use list comprehension on larger list")
print("3. When duplicates matter: Use custom functions that check and remove matched elements")
print("4. Always consider the specific requirements of your use case")
  1. 스크립트를 실행합니다.
python3 best_practices.py

이렇게 하면 다양한 시나리오에서 공통 요소를 찾는 모범 사례에 대한 포괄적인 가이드가 표시됩니다.

유틸리티 모듈 만들기

마지막으로, 향후 프로젝트에서 가져올 수 있는 재사용 가능한 유틸리티 모듈을 만들어 보겠습니다.

  1. 다음 내용으로 list_utils.py라는 새 파일을 만듭니다.
"""
List Utilities Module

A collection of functions for working with lists, including finding common elements.
"""

def find_common_elements(list1, list2, method='set', preserve_order=False, preserve_duplicates=False):
    """
    Find common elements between two lists.

    Parameters:
        list1 (list): First list
        list2 (list): Second list
        method (str): Method to use ('set', 'loop', or 'comprehension')
        preserve_order (bool): Whether to preserve the order of items from list1
        preserve_duplicates (bool): Whether to preserve duplicate common elements

    Returns:
        list: List of common elements
    """
    ## Handle the case with duplicates
    if preserve_duplicates:
        result = []
        list2_copy = list2.copy()

        for item in list1:
            if item in list2_copy:
                result.append(item)
                list2_copy.remove(item)

        return result

    ## When order matters but duplicates don't
    if preserve_order and not preserve_duplicates:
        lookup_set = set(list2)
        return [item for item in list1 if item in lookup_set]

    ## When neither order nor duplicates matter
    if method == 'set':
        return list(set(list1) & set(list2))
    elif method == 'loop':
        common = []
        for item in list1:
            if item in list2 and item not in common:
                common.append(item)
        return common
    elif method == 'comprehension':
        seen = set()
        return [item for item in list1 if item in list2 and not (item in seen or seen.add(item))]
    else:
        raise ValueError("Method must be 'set', 'loop', or 'comprehension'")

def list_difference(list1, list2):
    """
    Find elements in list1 that are not in list2.

    Parameters:
        list1 (list): First list
        list2 (list): Second list

    Returns:
        list: Elements in list1 but not in list2
    """
    return list(set(list1) - set(list2))

def list_union(list1, list2):
    """
    Find all unique elements from both lists combined.

    Parameters:
        list1 (list): First list
        list2 (list): Second list

    Returns:
        list: All unique elements from both lists
    """
    return list(set(list1) | set(list2))

## Usage examples
if __name__ == "__main__":
    ## Sample lists
    list1 = [1, 2, 3, 4, 5, 5]
    list2 = [4, 5, 5, 6, 7]

    print("Original lists:")
    print(f"List 1: {list1}")
    print(f"List 2: {list2}")

    print("\nCommon elements (using different methods):")
    print(f"Set method: {find_common_elements(list1, list2, method='set')}")
    print(f"Loop method: {find_common_elements(list1, list2, method='loop')}")
    print(f"Comprehension method: {find_common_elements(list1, list2, method='comprehension')}")

    print("\nWith order and duplicates preserved:")
    print(f"Preserving order: {find_common_elements(list1, list2, preserve_order=True)}")
    print(f"Preserving duplicates: {find_common_elements(list1, list2, preserve_duplicates=True)}")

    print("\nOther list operations:")
    print(f"Elements in list1 but not in list2: {list_difference(list1, list2)}")
    print(f"Elements in list2 but not in list1: {list_difference(list2, list1)}")
    print(f"All unique elements from both lists: {list_union(list1, list2)}")
  1. 스크립트를 실행하여 유틸리티 모듈이 작동하는지 확인합니다.
python3 list_utils.py
  1. 이제 새 스크립트에서 유틸리티 모듈을 가져와서 테스트해 보겠습니다. test_utils.py라는 파일을 만듭니다.
## Import our utility functions
from list_utils import find_common_elements, list_difference, list_union

## Creating some test data
fruits1 = ["apple", "banana", "cherry", "date", "banana"]
fruits2 = ["banana", "cherry", "fig", "grape", "banana"]

print("Fruits List 1:", fruits1)
print("Fruits List 2:", fruits2)

## Find common elements with different options
common_default = find_common_elements(fruits1, fruits2)
common_order = find_common_elements(fruits1, fruits2, preserve_order=True)
common_duplicates = find_common_elements(fruits1, fruits2, preserve_duplicates=True)

print("\nCommon fruits (default):", common_default)
print("Common fruits (preserving order):", common_order)
print("Common fruits (preserving duplicates):", common_duplicates)

## Find differences between lists
only_in_fruits1 = list_difference(fruits1, fruits2)
only_in_fruits2 = list_difference(fruits2, fruits1)

print("\nFruits only in list 1:", only_in_fruits1)
print("Fruits only in list 2:", only_in_fruits2)

## Find union of lists
all_unique_fruits = list_union(fruits1, fruits2)
print("\nAll unique fruits from both lists:", all_unique_fruits)
  1. 테스트 스크립트를 실행합니다.
python3 test_utils.py

다양한 옵션을 사용하여 유틸리티 함수를 보여주는 출력이 표시됩니다.

이 단계를 완료함으로써 다양한 방법의 성능 영향에 대해 배우고 향후 Python 프로젝트에 통합할 수 있는 재사용 가능한 유틸리티 모듈을 만들었습니다.

요약

이 Lab 에서 두 Python 리스트 간의 공통 요소를 찾는 다양한 기술을 배웠습니다. 다음을 탐구했습니다.

  1. 공통 요소를 찾는 다양한 방법:

    • 루프와 in 연산자 사용
    • Python 의 set 데이터 구조 및 교차 연산 사용
    • 리스트 컴프리헨션 (list comprehension) 사용
  2. 공통 요소를 찾는 것이 유용한 실제 응용 프로그램:

    • 소셜 네트워킹 (공통 관심사 찾기)
    • 쇼핑 목록 조정
    • 수강 신청 분석
  3. 성능 고려 사항 및 모범 사례:

    • Set 기반 방법은 일반적으로 큰 리스트에 가장 효율적입니다.
    • 요구 사항에 따라 순서 또는 중복을 유지해야 하는 경우
    • 리스트 연산을 위한 재사용 가능한 유틸리티 함수를 만드는 방법

이러한 기술을 통해 보다 효율적인 Python 코드를 작성하고 데이터 비교 및 분석과 관련된 실제 문제를 해결할 수 있습니다. 이제 Python 애플리케이션에서 리스트를 자신 있게 조작하고 특정 요구 사항에 따라 공통 요소를 찾는 적절한 방법을 선택할 수 있습니다.