[PYTHON] How to compare lists and retrieve common elements in a list

Sometimes I wanted to compare two lists with strings as elements and retrieve the common elements as a list. Well, I can do it, but I wondered how to do it myself and thought about it.

For example

Suppose you have two lists like this, tag_list and src_list, and you want to retrieve common elements as a list.

tag_list=['igarashi', 'kubo', 'iguchi']
src_list=['taniguchi', 'matsushita', 'koyama', 'asama', 
          'marui', 'igarashi', 'kubo', 'kondo']

tag_list has three elements. ʻIgarashiandkubo are also in src_list, but since there is no ʻiguchi, the expected value is['igarashi','kubo'].

1. Turn each list with a for statement to extract elements and compare them.

matched_list = []
for tag in tag_list:
    for src in src_list:
        if tag == src:
            matched_list.append(tag)

The first thing that came to my mind was, of course, this. It's easy to understand, but the indentation is deep and light.

2. One list is a for statement and the other is a filter function to retrieve and compare elements.

matched_list = []
for tag in tag_list:
    matched_list+=filter(lambda str: str == tag, src_list)

I wanted to use the list operation functions, filter (), map (), reduce (), so I tried my best. Is it intuitive for modern people who are accustomed to languages with abundant array manipulation functions?

3. Convert the list to set and AND it. Convert the result to a list

src_set = set(src_list)
tag_set = set(tag_list)
matched_list = list(src_set & tag_set)

When I googled, something like this suddenly came out. In a sense, it's intuitive. Is it the point that aggregate types have no order? I learned that it can be used in such cases.


So in the end, how is it best to write?

Is it easy to understand, readability, refreshing, python-like, and has advantages and disadvantages? I thought. More and more! Is there a way to write it? Also, is there a difference in processing speed? I was also worried. Next time, I will make a large sample data and measure it.


Sample source

cmp_list.py https://github.com/yamao2253/qiita

Recommended Posts

How to compare lists and retrieve common elements in a list
[python] Summary of how to retrieve lists and dictionary elements
How to clear tuples in a list (Python)
How to remove duplicate elements in Python3 list
How to count the number of elements in Django and output to a template
[Python] How to sort dict in list and instance in list
How to check in Python if one of the elements of a list is in another list
How to swap elements in an array in Python, and how to reverse an array.
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
How to create dataframes and mess with elements in pandas
[Python] How to delete rows and columns in a table (list of drop method options)
How to get a list excluding elements whose index is i ...?
How to delete multiple specified positions (indexes) in a Python list
How to split and save a DataFrame
[Python] How to convert a 2D list to a 1D list
How to get a stacktrace in python
How to use is and == in Python
How to get a specific column name and index name in pandas DataFrame
[Python] How to put any number of standard inputs in a list
I want to sort a list in the order of other lists
How to put a half-width space before letters and numbers in Python.
How to make a container name a subdomain and make it accessible in Docker
How to format a list of dictionaries (or instances) well in Python
How to stop a program in python until a specific date and time
[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement
How to use lists, tuples, dictionaries, and sets
Receives and processes n objects in a list
How to generate permutations in Python and C ++
How to create a JSON file in Python
Rewriting elements in a loop of lists (Python)
How to implement a gradient picker in Houdini
Get only the subclass elements in a list
How to notify a Discord channel in Python
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django
Sort list elements in a specified order in Python
How to write async and await in Vue.js
How to write a named tuple document in 2020
How to count numbers in a specific range
How to read a file in a different directory
How to Mock a Public function in Pytest
[Python] Manipulating elements in a list (array) [Sort]
How to plot autocorrelation and partial autocorrelation in python
How to pass the execution result of a shell command in a list in Python
How to achieve something like a list of void * (or variant) in Go?
How to read a serial number file in a loop, process it, and graph it
[Pandas] How to check duplicates and delete duplicates in a table (equivalent to deleting duplicates in Excel)
How to get a list of files in the same directory with python
How to specify a schema in Django's database settings
How to retrieve the nth largest value in Python
How to convert / restore a string with [] in python
How to define Decorator and Decomaker in one function
Differences in behavior between append () and "+ =" operators when adding data to a list in Python
How to identify the element with the smallest number of characters in a Python list?
How to list files under the specified directory in a list (multiple conditions / subdirectory search)
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
[Python] How to expand variables in a character string
How to write a list / dictionary type of Python3
A memorandum on how to use keras.preprocessing.image in Keras
Things to note when initializing a list in Python