python learning notes

If the python version does not switch to the latest version

If pyenv does not switch the python version, use the following command.

$ eval "$(pyenv init -)"

Syntax memo

What is a data type?

It has attributes (variables) and methods (functions). A class in PHP? However, initialization (storage in a variable) is not necessary to use a data type function. Data type. Available in function ()

Functions of data type

Each data type such as split () of a character string has a function. This function is called ** method **. The method is a variable. Execute with the method name ()

a = 'tokyo,shibuya'
b = a.split(',')
print(b) # ['tokyo','shibuya']

How to make a function

Construction

def function name(argument)
processing
	return x

Set the default value for the argument

def function name(argument=Default value)
processing
	return x

How to create a data type (class)

#Dice data
class Dice :
  def __init__(self,val=6): # ①
  	if val not in [4,6,8,12,20]:
  		raise Exception('There is no such front body') #②
  	self.face_num = val #③
  def shoot(self):
    return random.randint(1,self.face_num)

① You can specify the function to be executed when it is called (initialized) by the function of __init__. ② It is possible to display an error with raise. The numerical value of the argument is checked in the if argument in target. Error messages in parentheses for exception ('') can be displayed ③ self must be specified as an argument when creating a method in the class. Also, prefix the variables used in the methods in the class with self.

Class inheritance

class class name(Inheritance source data type):
	#When adding processing to the initialization method, also load the initialization method of the parent class
	def __init__(self) :
		super(name of the class,self).__init__()
		#super has two arguments, a data type and self, and returns its parent class.
Additional processing
		

Creating an object from a class

class A() :
	age = 37

a = A()
a.age # 37

An object can be created by assigning the class name () to a variable. Note that if you do not add (), it will be just a copy of the class!

class A() :
	age = 37

a = A
a.age = 20

a.age # 20
A.age # 20

b= A()
b.age #20

If you copy it, you will change the variable of the class when you try to change the variable of the object as described above, and when you create the object after that, that value will be the initial value.

Meaning of self

Meaning to put yourself in the argument. Class has methods and variables

Function memo

Count the number of characters

len()

Convert to string

str()

Output data to screen

print()

Create a list

Creates a contiguous list of integers for the number specified in int. The start position and end position can be determined by separating the arguments with. Start with the first argument. Before the second argument.

range(3)     # [0,1,2]
range(1,5)   # [1,2,3,4]
range(10,11) # [10]

Functions that string type has

Separate strings with specific characters

The method that the string has. Separates the character string with the character specified in the argument and returns the result as an array.

a = 'tokyo,nagoya'
b = a.split(',')
print(b) #[tokyo, nagoya]

Uppercase the string

String.upper()
a = 'abcd'
b = a.upper()
print(b) # ABCD

Returns the appearance position of a specific character

Returns the first occurrence position of the character specified in the argument with 0 at the beginning

a = 'abcdefg'
b = a.index('c')
print(b) # 2

Module memo

Module loading

import module name
Module name.function

Others You can use as to name the module

import module name as A
A.function#=Module name.function

Random value generation

import random
#Random display of range-separated integer values
random.randint(1,100)
#Randomly display the values in the array
random.random.choice(Array or string)

Built-in functions

Adapt functions to all lists map

map(function,list)
map(str,[1,2,3]) #['1','2','3']

Date and time display

import datetime
#Date representation
b = datetime.date(2013,12,11)
print(b) #2013-12-11
#Calculation of the day of the week (0 is Monday,6 is sunday)
c = b.weekday() 
print(c) # 2

Functions / features of list type

Get the number of items len

a = [1,2,3]
len(a) # 3

Get the last item

a = [1,2,3]
a[-1] # 3
a[-2] # 2

Add element append

a = [1,2,3]
a.append(4)
print(a) # [1,2,3,4]

Add element to specific position append

a = [1,2,3]
a.insert(1,5)
print(a) #[1,5,2,3]

Delete element pop

a = [1,2,3]
a.pop(2)
print(a) #[1,2]

Remove the element with the specified value remove

a = ['da','ai','oo']
a.remove('ai')
print(a) #['da','oo']

List join extend

a = [1,2]
b = [3,4]
a.extend(b)
print(a) #[1,2,3,4]

Get the total of the list

a = [1,2,3]
b = sum(a)
b # 6

Get the maximum and minimum of the list

a = [1,2,3]
b = max(a) # 3
c = min(c) # 1

Cut out the list

a = [1,2,3,4,5,6,7,13,15]
a[0:3] #[1,2,3]
a[2:5] #[3,4,5]
a[3:]  #[4,5,6,7,13,15]
a[:3]  #[1,2,3]

Sorting the list

a = [3,2,1,4,5,6]
#Sort in ascending order
a.sort()
a # [1,2,3,4,5,6]
#Sort in reverse order
a.reverse()
a # [6,5,4,3,2,1]

Strings are also sorted in lexicographic order (uppercase> lowercase)

Creating an empty list

a = []

Functional

String concatenation

a = 'Inside'
b = 'Soto'
c = a + 'When' + c
c #Nakatosoto

Check if it is included

a = '12345'
if '3' in a :
	print 'true'

Execute a function on each numerical value of the array

#Cast each element of the array as an example
a = [1,2,3]
a_str = map(str,a)
a_str # ['1','2','3']

Regular expressions

Search and retrieve the applicable ones

import re
c = 'My age is 65 years old'
pat = r"(\d{1,2})age"
d = re.search(pat,c)
d.group(1) # 65

Replacement / repositioning

re.sub(r'pattern','Replacement character',Target data)
#Example
import re
a = 'my name is ryo, i like programing'
n = re.sub(r"\w*(ryo)\w*",'yu',a)
n # 'my name is yu, i like programing'
#Replace word position. Of the pattern()When replacing\Since it can be specified by a number, use it.
a = '1is2 3is4 5is6'
b = re.sub(r"(\d)is(\d)",r"\2is\1",a)
b # '2is1 4is3 6is5'

Lambda expression

What is a lambda expression?

A function that does not have a function name is called an anonymous function. It is mainly used by putting it in a variable. It is also convenient to use it in a map that executes a function for each element of list or a filter that selects each element of list by a function.

lis = range(1,11) # [1,2,3,4,5,6,7,8,9,10]

#Take an even number from lis
lis_even = list(filter(lambda a : a % 2 == 0,lis))
print(lis_even) # [2,4,6,8,10]

#Triple each element of lis
lis_x3 = list(map(lambda a : a * 3, lis))
print(lis_x3) # [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

Recommended Posts

Python learning notes
python learning notes
python learning
O'Reilly python3 Primer Learning Notes
Python data analysis learning notes
[Python] Learning Note 1
Python study notes _000
Python beginner notes
python learning output
Python study notes_006
Python learning site
Python learning day 4
python C ++ notes
Python Deep Learning
Python study notes _005
Python grammar notes
Python Library notes
Python learning (supplement)
Deep learning × Python
python personal notes
python pandas notes
Python study notes_001
Python3.4 installation notes
Notes on PyQ machine learning python grammar
Learning notes from the beginning of Python 1
Learning notes from the beginning of Python 2
Python class (Python learning memo ⑦)
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python
Python module (Python learning memo ④)
missingintegers python personal notes
Reinforcement learning 1 Python installation
Learning Python with ChemTHEATER 05-1
Python ~ Grammar speed learning ~
Python: Unsupervised Learning: Basics
Python package development notes
Device mapper learning notes
python decorator usage notes
Python ipaddress package notes
Private Python learning procedure
Learning Python with ChemTHEATER 02
Python Pickle format notes
[Python] pytest-mock Usage notes
Learning Python with ChemTHEATER 01
First Python miscellaneous notes
Python: Deep Learning Tuning
Matlab => Python migration notes
Python: Supervised Learning (Regression)
Notes around Python3 assignments
Notes using Python subprocesses
Python framework bottle notes
Python: Supervised Learning (Classification)
Python notes using perl-ternary operator
Effective Python Learning Memorandum Day 15 [15/100]
Python exception handling (Python learning memo ⑥)
Python
Effective Python Learning Memorandum Day 6 [6/100]
Basics of Machine Learning (Notes)
Effective Python Learning Memorandum Day 12 [12/100]
Python standard unittest usage notes
Python notes to forget soon