2 つの Python リストで共通要素を見つける方法

PythonBeginner
オンラインで実践に進む

はじめに

Python のリストは、データのコレクションを格納し整理するための基本的なデータ構造です。2 つのリスト間の共通要素を見つけることは、データ分析から Web アプリケーションの構築まで、多くのプログラミングシナリオで役立つ実用的なスキルです。この実践的な実験(Lab)では、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 リストの基本を理解したので、2 つのリスト間の共通要素を見つける準備ができました。次のステップで使用する 2 つのサンプルリストを作成しましょう。

  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

これにより、次のステップで共通要素を見つけるために使用する 2 つのリストが表示されます。

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 リストの作成と探索に成功しました。次のステップでは、これら 2 つのリスト間の共通要素を見つける方法を学びます。

さまざまな方法を使用した共通要素の検索

2 つのリストができたので、それらの間の共通要素を見つけるための複数の方法を調べてみましょう。各メソッドには利点があり、それらすべてを理解することで、特定のニーズに合った適切なアプローチを選択するのに役立ちます。

方法 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 番目のリスト全体を検索する必要があるためです。

方法 2:セットの使用

より効率的なアプローチは、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:リスト内包表記の使用

リスト内包表記は、既存のリストに基づいてリストを作成するための簡潔な方法を提供します。これを使用して、1 行のコードで共通要素を見つけることができます。

  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]

リスト内包表記は、ループメソッドよりも簡潔で、要素の順序を保持しますが、ループメソッドと同じパフォーマンス特性があります。

すべての方法の比較

3 つすべての方法を比較するファイルを作成しましょう。

  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]

3 つすべてのメソッドで同じ結果が得られます。list1list2 の間の共通要素は [4, 5, 6] です。

これで、Python で 2 つのリスト間の共通要素を見つけるための 3 つの異なる方法を学びました。次のステップでは、これらのテクニックの実用的なアプリケーションをいくつか探ります。

共通要素を見つける実用的なアプリケーション

リスト間の共通要素を見つけることが役立つ、いくつかの現実世界のアプリケーションを調べてみましょう。前のステップで学習した方法を使用して、これらの例を実装します。

アプリケーション 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:買い物リストの比較

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

3 つの方法のパフォーマンス比較が表示され、さまざまなリストサイズの実行時間が表示されます。出力は次のようになります(実際の時間は異なります)。

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 プロジェクトに組み込むことができる再利用可能なユーティリティモジュールも作成しました。

まとめ

この実験では、2 つの Python リスト間の共通要素を見つけるためのさまざまなテクニックを学習しました。以下を探索しました。

  1. 共通要素を見つけるためのさまざまな方法:

    • ループと in 演算子の使用
    • Python の set データ構造と交差演算の使用
    • リスト内包表記の使用
  2. 共通要素を見つけることが役立つ実用的なアプリケーション:

    • ソーシャルネットワーキング(共通の興味の検索)
    • 買い物リストの調整
    • コース登録の分析
  3. パフォーマンスに関する考慮事項とベストプラクティス:

    • セットベースの方法は、一般的に大きなリストに対して最も効率的です。
    • 要件に基づいて、いつ順序または重複を保持するか。
    • リスト操作のための再利用可能なユーティリティ関数の作成方法。

これらのスキルにより、より効率的な Python コードを記述し、データの比較と分析に関連する現実世界の問題を解決できるようになります。これで、Python アプリケーションでリストを自信を持って操作し、特定の要件に基づいて共通要素を見つけるための適切な方法を選択できます。