Home > Backend Development > Python Tutorial > Summary of common methods and techniques in Python

Summary of common methods and techniques in Python

伊谢尔伦
Release: 2017-06-28 13:19:55
Original
1466 people have browsed it

This article mainly introduces some common Python methods and techniques in the collection. This article explains three methods of reversing string, four methods of traversing a dictionary, three methods of traversing a list, and a dictionary. Sorting methods and other Pythoncommon tips and methods, friends in need can refer to the following

1. Three methods of reversing strings
1.1 . Simulate the method in C++ and define an empty string to achieve
by setting an empty string, then traverse the strings in the parameters from back to front, and use string addition to merge them into new strings

def reverse(text) :
    str = ''
    index = len(text) - 1
    while index >= 0 :
        str += text[index]
        index -= 1
    return str
Copy after login


1.2. Use the slicing method
This is a feature in Python. Slicing can take negative values. This is the slicing method. Set the step size to - 1. This achieves reverse sorting.

def reverse_1(text) :
    return text[::-1]
Copy after login

1.3. Using a list

Use the reverse method of the list, first convert the text into a list, then reverse it through the reverse method, and then connect it into characters through join string.

def reverse_2(text) :
    temp = list(text)
    temp.reverse()
    return ''.join(temp)
Copy after login

2. Use reduce
Use anonymous function and reduce()

def reverse_3(text) :
    return reduce(lambda x, y : y + x, text)
print reverse_3("Hello")
Copy after login

3. Four ways to traverse the dictionary Method

dict={"a":"apple","b":"banana","o":"orange"} 
 
print "##########dict######################" 
for i in dict: 
        print "dict[%s]=" % i,dict[i] 
 
print "###########items#####################" 
for (k,v) in  dict.items(): 
        print "dict[%s]=" % k,v 
 
print "###########iteritems#################" 
for k,v in dict.iteritems(): 
        print "dict[%s]=" % k,v 
 
print "###########iterkeys,itervalues#######" 
for k,v in zip(dict.iterkeys(),dict.itervalues()): 
        print "dict[%s]=" % k,v
Copy after login


4. Three methods of traversing list

for key in lst :
    print key
    
for i in range(len(lst)) :
    print lst[i]
for index, key in enumerate(lst) :
    print key    //index是list的索引
Copy after login


5. Dictionary sorting method
The dictionary is sorted according to the value of value from large to small (default is sorted from small to small).

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict
//输出的结果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
Copy after login

Let’s decompose the code below
print dic.iteritems() to get a list of [(key, value)].
Then use the sorted method, through the key parameter, to specify that the sorting is based on value, that is, the value of the first element d[1. reverse = True means that it needs to be flipped. The default is from small to large. If it is flipped, it will be from large to small.
Sort the dictionary by key:

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[0]) # d[0]表示字典的键
print dict
#sorted中第三个可选参数为reverse, True表示从大到小排序
#默认reverse = False
Copy after login

6. Subclass and parent class
SubclassConstructorCall the initialization constructor of the parent class Function

class A(object) :
    def init(self) :
        print  "testA
class B(A) :
    def init(self) :
        A.init(self)
Copy after login


The subclass calls the function of the same name of the parent class

super().fuleifunction()
Copy after login


7. More flexible parameter passing method

func2(a=1, b=2, c=3) #默认参数
func3(*args)         #接受任意数量的参数, 以tuple的方式传入
func4(**kargs)       #把参数以键值对字典的形式传入
Copy after login

Prefix the variable with an asterisk (*), and the parameters during the call will be stored in a tuple()object and assigned to the formal parameters. Within the function, when you need to process parameters, you only need to operate on the formal parameters of this tuple type (here, args). Therefore, the function does not need to specify the number of parameters when defining it, and can handle any number of parameters.

def calcSum(*args):
    sum = 0
    for i in args:
        sum += i
        print sum
#调用:
calcSum(1,2,3)
calcSum(123,456)
calcSum()
#输出:
6
579
0
#################################
def printAll(**kargs):
    for k in kargs:
    print k, ':', kargs[k]
printAll(a=1, b=2, c=3)
printAll(x=4, y=5)
#输出:
a : 1
c : 3
b : 2
y : 5
x : 4
Copy after login

Python's parameters can be combined in many forms. When using them in a mixed manner, you must first pay attention to the way the function is written. You must abide by:

1. Formal parameters with default values ​​(arg =) must be after the formal parameter (arg) without default value
2. Tuple parameter (*args) must be after the formal parameter (arg=) with default value
3. Dictionary parameter (** kargs) must come after the tuple parameters (*args)

When the function is called, the parameter passing process is:

1. Assign the actual parameters without specified parameters to the form in order Parameters
2. Assign the actual parameters of the specified parameter name (arg=v) to the corresponding formal parameters
3. Pack the extra actual parameters without specified parameters into a tuple and pass it to the tuple parameter (*args )
4. Pack the extra actual parameters with specified parameter names into a dict and pass it to the dictionary parameters (**kargs)

8. lambda expression
lambda expression The formula can be regarded as an anonymous function
The syntax format of lambda expression:
Lambda parameter list: expression #There are no parentheses around the parameter list, there is no return keyword before the return value, and there is no function name

def fn(x):
    return lambda y: x + y
#调用
a = fn(2)
print a(3)
#输出
5
Copy after login

Analysis
: After fn(2) is called, it is equivalent to a = lambda y: 2 + y, and then when a(3) is called.
It is equivalent to print lambda y: 2 + 3

The above is the detailed content of Summary of common methods and techniques in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template