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.
--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 sys
Must be done first
Example
sys.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*
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 | function | comment |
---|---|---|
** | Exponentiation |
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で削除する方法 |
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)
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
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.
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
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
# -*- coding: utf-8 -*-
>>> 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))
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)
results_vector = np.linalg.solve(A_matrix,T_vector)
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
print type(obj) #Mold
print dir(obj) #method list
Recommended Posts