Super cool de-Python syntax to remember

Introduction

I'm new to Python __ "Let's do this more" __ __ "How to write" __ __ "Die!" __ I think there are opinions, but please feel free to write in the comments!

This article is based on Python 3! It's not divided by order, type or difficulty.

Part 1. enumerate

Enumerate means "count" in English, but it remains the same. Maybe it's often used in for statements?

code

Addendum: Fixed the problem that the order of s and i was reversed. Currently the code has been fixed.

python


l = list("abcde") # ['a', 'b', 'c', 'd', 'e']

for (i,s) in enumerate(l): #The element of l is assigned to s, and 1 is assigned to i.,2,3 ... and so on
    print("{}: {}".format(i,s))

output

0: a
1: b
2: c
3: d
4: e

Part 2. zip

The zip function is never __ a function that handles zip files! !! !! !! __ I think that this is also used quite a bit in the for statement. __ A function used when you want to repeat two variables together __

code

python


alphabet = list("abcde")  # ['a', 'b', 'c', 'd', 'e']
number = list(range(1,6)) # [1, 2, 3, 4, 5]

for (s,i) in zip(alphabet, number): #Substitute alphabet for s and number for i
   print("{}: {}".format(s,i))

result

a: 1
b: 2
c: 3
d: 4
e: 5

Part 3. lambda expression

It's called an anonymous function __. I will explain it a little carefully.

First, let's say you have a function like this

python


def square(x): #square function, squares x and returns
   return x**2

square(5) #25
square(10) #100

It's a simple function that just squares the given argument x and returns it. If you write this as a lambda expression, it will look like this.

Addendum: From the comment, it was pointed out that assigning a lambda expression to a variable is a violation of PEP8, so I modified the sample.

python


ans = map(lambda x: x**2, [5, 10]) #Apply lambda expression processing to 5 and 10(The map will be described later)
print(list(ans)) # [25, 100]

The code will be simpler.

Postscript: There was a comment about the merit, so I corrected it.

Part 4. map

I use the map function a lot. __ A function __ that processes all elements at once.

code

python


string_l = list("0123456789") 

"""
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
#At this point the type of all elements in the variable l is str
#I want to make all this int type
"""

int_l = list(map(int, string_l))

#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this way, we were able to collectively change the elements of a list of str type only to int.

It's so convenient that it will change your life if you remember it. really.

Recommended Posts

Super cool de-Python syntax to remember
Linux commands to remember
A super introduction to Linux
Easy to make with syntax
Super introduction to machine learning