Python cheat sheet (for C ++ experienced)

Purpose: People who have learned C language "enjoy" learning python (only python-specific notations and rules are described)

However, since it is a cheat sheet, it only teaches the existence of the function, and detailed explanation is not described for the sake of good visibility.

Python-wide rules

--No need for explicit typing --Everything is an object (functions also have member variables) --Since the function itself is the first object, the function name can be used as an argument or return value of the function. --Subroutines do not exist (including None, which always has a return value)

-Each time you call a function, a namespace is created for the local variables in that function and released when you exit the function. -Everything is passed by reference except for the assignment of immutable objects -if and for are not scoped

##Function definition -def function name(Argument 1,Argument 2,...) -Named arguments allow the arguments to be in any order(C++Features not found in)

However, if a named argument appears when reading the argument list from left to right, the subsequent arguments must be named.(Named arguments are right-justified)。

-Default value available for argument(C++the same as.)

C due to the presence of named arguments++More default value can be set(Because the order of the arguments is free depending on the named argument)

c++Must have default values right justified

-No header file required to define function

-No need to specify the return type in the function definition(No typing required)

##import (#Corresponding to include)

import sysMust be done first

Examplesys.path.insert(0, new_path) Module name.name of the class.Function name()

###Use from to load the classes in the module into the global namespace(Module name can be omitted)

Example ``` from sys import path from module name import class name

So when you want to call all the classes in a module from module name import*

Data type

Built-in type

Model name function Specific contents
Bool True or false True False ,0 ≠ true 0=false
Numerical value Integer, decimal, complex(cast is truncated) 1, 1.0,
list An array that can store any Brzeg(listの要素にlistも代入可) a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
Tuple Locked so that it cannot be changed to the list(もとのTupleが破壊的変更を受けるメンバ関数なし) a_tuple=('a', 'b', 'mpilgrim', 'z', 'example')
set Unordered, non-duplicate list a_set ={'a', 'b', 'mpilgrim', 'z', 'example'}
dictionary(Set with key) Set of key / value pairs(Keys can be used instead of indexes in sets)The key is unique a_dict = {'key1': 'value1', 'key2': 'value2'}
NoneType Types that handle only null null is unique to NoneType

operator

operator function comment
** Exponentiation

Operations on lists

function Method comment
Access to elements a[indesx] Boundary is periodica[-1]Points to the last element
Slice to generate subsequence a[n:m] n<=i<m a[i]Is extracted as a list.a[:]Refers to all elements
Add element a.append(n) a.insert(n,m) append is added at the end, n is added at the mth,+You can also combine lists with
Add element(Using a list) a.extend([list]) extend is added at the end, taking a list object as an argument
Delete element del a[1] a.remove('Element name') 位置で削除する方法と、具体的なElement nameで削除する方法

loop

The following loop is useful

for i,word in enumerate(['a','b','c']):
  print i,word

Output result

0 a
1 b
2 c
for i in range(0,11,1) 

Reading and writing files

Numbers cannot be written directly in python (read / write is a string or binary) So in order to treat it as a number, float (a) and str (a) are required.

f = open('text.txt', 'r')
addressList = []
for line in f:
    name, zip, address = line[:-1].split('\t')
    print name, zip, address
	addressList.append(float(address))

Numbers should be cast to float as soon as they are read

closure

Clojure is a function in which a function defined outside the global scope stores information about the scope that surrounds you at "at the time of definition". Functions required in python that can define functions in functions

clojures.py


>>> def outer():
...     x = 2
...     def inner():
...         print x
...     return inner
>>> foo = outer()   #inner function returns
>>> foo()
2	#Remember 2 which is not in the scope of the inne function

You can use this to generate a customized function that takes fixed arguments.

Decorator

Add a function to a function (using the mechanism that takes the original function as an argument, adds the function, and reassigns the arranged function to the original function) Can be abbreviated using @

Load the function to output the log using the decoder.py


def logger(func):
     def inner(*args, **kwargs): #Create a function with added functions
         print "Arguments were: %s, %s" % (args, kwargs)
         return func(*args, **kwargs) #Any underlying function
     return inner
          
#Add logger to foo function
@logger
def foo(x, y):
     return x * y
#this@logger def foo is foo=logger(foo)Syntax sugar

foo(2,3)
Arguments were: (2, 3), {}
6

Intensional expression

The list can be generated as follows. Create a list with f (x) as an element using x that satisfies the condition P (x) among the elements x contained in S. By the way, if can be omitted as an option (the second example is a generator)

[f(x) for x in S if P(x)] 
max(x*x for x in [1,5,3] if x<3)

Tips

Make a comment in Japanese

# -*- coding: utf-8 -*-

Index of maximum value in list

>>> a = [2,3,4,3,4,4,4]
>>> b = [i for i,j in enumerate(a) if j == max(a)]
>>> b
[2, 4, 5, 6]

#When there is one maximum element
>>>a.index(max(a))

Matrix generation (array to MxN matrix)

    A = []
    for i in range(0,M+1):
            for j in range(0,N+1):
                tmp = i+j
                A.append(tmp)
    A = array(A).reshape(M,N)

Solve linear equations

results_vector = np.linalg.solve(A_matrix,T_vector)

Graph

import matplotlib.pyplot as plt


plt.plot( [1,2,3], '-')  #Line
plt.plot( [1,2,3], '--') #Dashed line
plt.plot( [1,2,3], '-.') #Dashed line
plt.plot( [1,2,3], ':')  #dotted line
plt.plot( [1,2,3], '.')  #point
plt.plot( [1,2,3], ',')  #Dot
plt.plot( [1,2,3], 'o')  #Circle
plt.plot( [1,2,3], 'v')  #Downward triangle
plt.plot( [1,2,3], '^')  #Upward triangle
plt.plot( [1,2,3], '<')  #Left-pointing triangle
plt.plot( [1,2,3], '>')  #Right-pointing triangle
plt.plot( [1,2,3], 's')  #square
plt.plot( [1,2,3], 'p')  #pentagon
plt.plot( [1,2,3], 'h')  #Hexagon(Vertical)
plt.plot( [1,2,3], 'H')  #Hexagon(side)
plt.plot( [1,2,3], '+')  #cross
plt.plot( [1,2,3], 'x')  #X
plt.plot( [1,2,3], 'd')  #Rhombus
plt.plot( [1,2,3], 'D')  #square(Diagonal)
plt.plot( [1,2,3], '|')  #Vertical line
plt.plot( [1,2,3], '_')  #horizontal line

#Matching technique
plt.plot( [1,2,3], '-o')   #Line+Circle
plt.plot( [1,2,3], '--o')  #Dashed line+Circle

plt.plot( [1,2,3], 'b') #Blue
plt.plot( [1,2,3], 'g') #Green
plt.plot( [1,2,3], 'r') #Red
plt.plot( [1,2,3], 'c') #cyan
plt.plot( [1,2,3], 'm') #Magenta
plt.plot( [1,2,3], 'y') #yellow
plt.plot( [1,2,3], 'b') #black
plt.plot( [1,2,3], 'w') #White

#Simultaneous specification with plot method
plt.plot( [1,2,3], '--b') #Dashed line+Blue
plt.show() #drawing
plt.savefig("graph.png ") #Save

Examine types and methods

print type(obj) #Mold
print dir(obj) #method list

Recommended Posts

Python cheat sheet (for C ++ experienced)
AtCoder cheat sheet in python (for myself)
PySpark Cheat Sheet [Python]
Python sort cheat sheet
[Updating] Python Syntax cheat sheet for Java shop
[Python3] Standard input [Cheat sheet]
Python Django Tutorial Cheat Sheet
Apache Beam Cheat Sheet [Python]
Tips for calling Python from C
Python Computation Library Cheat Sheet ~ itertools ~
Blender Python Mesh Data Access Cheat Sheet
Mathematical Optimization Modeler (PuLP) Cheat Sheet (Python)
R code compatible sheet for Python users
An introduction to Python for C programmers
2016-10-30 else for Python3> for:
python [for myself]
python C ++ notes
python, openFrameworks (c ++)
Curry cheat sheet
SQLite3 cheat sheet
pyenv cheat sheet
Create a C array from a Python> Excel sheet
Boost.NumPy Tutorial for Extending Python in C ++ (Practice)
Wrap C ++ with Cython for use from Python
About Python for loops
[For data science] Oreore Jupyter cheat sheet [Jupyter Notebook / Lab]
conda command cheat sheet
PIL / Pillow cheat sheet
Python basics ② for statement
Linux command cheat sheet
Benchmark for C, Java and Python with prime factorization
About Python, for ~ (range)
Spark API cheat sheet
[Introduction to python] A high-speed introduction to Python for busy C ++ programmers
python textbook for beginners
Refactoring tools for Python
python for android Toolchain
Go language cheat sheet
Deep Learning Experienced in Python Chapter 2 (Materials for Journals)
C API in Python 3
ABC147 C --HonestOrUnkind2 [Python]
Python pdf cheat sheets
Settings for testing C ++ 11 Python modules on Travis CI
OpenCV for Python beginners
Install Python (for Windows)
[Python] for statement error
Programming with your smartphone anywhere! (Recommended for C / Python)
Python environment for projects
Newton's method in C ++, Python, Go (for understanding function objects)
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
Extend python in C ++ (Boost.NumPy)
tox configuration file cheat sheet
Python memo (for myself): Array
About Fabric's support for Python 3
Python list, for statement, dictionary
ABC163 C problem with python3
Python for Data Analysis Chapter 4
Python, Java, C ++ speed comparison
Modern Python for intermediate users
Learning flow for Python beginners
Python 3.6 installation procedure [for Windows]