[Python] How do you use lambda expressions? ?? [Scribbles] [Continued-1]

Reason for publication

・ I posted the Lambda expression code to qiita the day before, but it violates PEP8 and the lambda expression works. I thought it wouldn't lead to self-growth if I seemed to confirm it. While understanding how to use the map function and filter function that are often rolled on the net, I felt the value of the lambda expression.

The one I mentioned in qiita last time

[Python] How do you use lambda expressions? ?? [Scribbles] [First post] https://qiita.com/sho_cullni/items/aba9a09b30abb20cfd1a

map function

● Grammar

A function that executes function processing on a list and outputs a return value

map(function,List etc.)

● Sample code

I made a code that triples for a given list

map_test.py


num_list = [-4, -3, -2, -1, 0, 1, 2, 3, 4]

triple_num_list = map(lambda x: x * 3, num_list)
print(list(triple_num_list))

If you want to reproduce the above code using def, for example:

def triple(x):
    x = x * 3
    return x

num_list = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
print(list(map(triple,num_list)))

The output result when the above two codes are executed is as follows

[-12, -9, -6, -3, 0, 3, 6, 9, 12]

filter function

● Grammar

A function that executes a function on a list, etc., and outputs only those that meet the conditions (becomes True) as return values.

filter(function,List etc.)

● Sample code

I made a code that retrieves multiples of 3 for a given list (A feeling of Nabeatsu in the world)

filter_test.py


num_list = [1, 2, 3, 4, 5, 6]
aho = filter(lambda x: x % 3 == 0, num_list)
print(list(aho))

If you want to reproduce the above code using def, for example:

def ahoaho(x):
    for i in x:
        if i % 3 == 0:
            aho.append(i)

aho = []
num_list = [1, 2, 3, 4, 5, 6]

ahoaho(num_list)
print(list(aho))

The output result when the above two codes are executed is as follows

[3, 6]

Impressions

-Sure, it seems easier to code than defining each function with def. .. .. !! -The combination technique of filter function and lambda expression can be used for web scraping. If you can understand it in a good way in the future, I will list it on qiita.

sorted function, max function, min function (Added on July 29, 2020)

I have commented, so I will add it! Thank you for your comment every time! (^^) / I hope to update in the future what happens when I write in def ...!

Also, to be exact, it is not a lambda function, but a lambda expression. Excuse me. I have fixed it!

● Grammar

・ You can do the following with the following grammars sorted function: Sorts in ascending or descending order according to the result of the function. max function: Extracts the largest data for the result of the function. min function: Extracts the smallest data for the result of the function.

sorted(List etc.,function)・ ・ ・ Max and min are the same, so it may be good to remember them together!

● Sample code

・ It may not be a good subject, but the number of people infected with coronavirus is easy to imagine. Try sorting, listing the prefectures with the most infections, and vice versa.

sample.py


corona_infected = [["Tokyo", 11611],["Saitama", 2142],["Chiba",1512],["kanagawa", 2283]]
 
#Code example of sorted function, max function, min function
corona = sorted(corona_infected, key=lambda x: x[1])
corona_max = max(corona_infected,key=lambda x: x[1])
corona_min = min(corona_infected,key=lambda x: x[1])

#Output to console
print(corona_infected)
print(corona)
print(corona_max)
print(corona_min)

The output result when the above two codes are executed is as follows

[['Tokyo', 11611], ['Saitama', 2142], ['Chiba', 1512], ['kanagawa', 2283]]
[['Chiba', 1512], ['Saitama', 2142], ['kanagawa', 2283], ['Tokyo', 11611]]
['Tokyo', 11611]
['Chiba', 1512]

Recommended Posts

[Python] How do you use lambda expressions? ?? [Scribbles] [Continued-1]
How to use Python lambda
% And str.format () in Python. Which one do you use?
What is pip and how do you use it?
How much do you know the basics of Python?
How to install and use pyenv, what to do if you can't switch python versions
python3: How to use bottle (2)
[Python] How to use list 1
How to use Python argparse
Use regular expressions in Python
Python: How to use pydub
[Python] How to use checkio
[Python] How to use virtualenv
python3: How to use bottle (3)
How do you collect information?
python3: How to use bottle
How to use Python bytes
[Python] How to do PCA in Python
Python: How to use async with
[Python] How to use Pandas Series
How to use Requests (Python Library)
Do you need a Python re.compile?
How to use SQLite in Python
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
Indispensable if you use Python! How to use Numpy to speed up operations!
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
[Python] How to use Typetalk API
Python | What you can do with Python
How many types of Python do you have in Windows 10? I had 5 types.
Python --How do you split a list into evenly sized chunks in Python?
[Python] Summary of how to use pandas
Use print in a Python2 lambda expression
How to install and use pandas_datareader [Python]
How to do R chartr () in Python
[python] How to use __command__, function explanation
[Python] How to use import sys sys.argv
How to do portmanteau test with python
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
How to access RDS from Lambda (python)
Don't use \ d in Python 3 regular expressions!
python: How to use locals () and globals ()
How to use __slots__ in Python class
How to use "deque" for Python data
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
Until you can use opencv with python
How to use is and == in Python
[Blender x Python] How to use modifiers
[Question] How to use plot_surface of python
How to build an environment when you want to use python2.7 after installing Anaconda3