Some Python common methods and techniques to collect

Source: Internet
Author: User
Tags anonymous constructor join sort

This article mainly introduces some of the favorite Python methods and techniques, this article explains three ways to reverse the string, four ways to traverse the dictionary, three ways to traverse the list, dictionary sorting methods and other Python common techniques and methods, need friends can refer to the

1. Three ways to reverse a string

1.1. Simulate C + + method, define an empty string to implement

The string is merged into a new string by setting an empty string and then talking about the strings in the argument, traversing from the back forward, using the addition of strings

The code is as follows:

def reverse (text):

str = '

index = len (text)-1

While index >= 0:

str = Text[index]

Index-= 1

Return str

1.2. Using Slicing method

This is an attribute in Python where slices can take a negative value, which is a slicing method that sets the step to-1, which enables the reverse ordering.

The code is as follows:

def reverse_1 (text):

return Text[::-1]

1.3. Using the list

Using the reverse method of the list, first converts the text to a list, then reverses it through the reverse method, and then joins the string through a join.

The code is as follows:

def reverse_2 (text):

temp = List (text)

Temp.reverse ()

Return '. Join (temp)

2. Use reduce

Use anonymous functions and reduce ()

The code is as follows:

def reverse_3 (text):

return reduce (lambda x, Y:y + x, text)

Print Reverse_3 ("Hello")

3. Four ways to traverse a dictionary

The code is as follows:

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

4. Three ways of traversing list

The code is as follows:

For key in LST:

Print key

For I in range (len (LST)):

Print Lst[i]

For index, key in Enumerate (LST):

The print key//index is the index of the list

5. Dictionary sorting method

Dictionaries are sorted in order of value values from large to small (by default small to sort).

The code is as follows:

DIC = {' A ':, ' BC ': 5, ' C ': 3, ' ASD ': 4, ' AA ': ",", ' d ': 0}

dict= Sorted (Dic.iteritems (), Key=lambda d:d[1], reverse = True)

Print Dict

Results of output:

[(' AA ',], (' A ', "), (' BC ', 5), (' ASD ', 4), (' C ', 3), (' d ', 0)]

Let's decompose the code below.

Print Dic.iteritems () gets a list of [(Keys, values)].

And then using the sorted method, by using the key parameter, the ordering is sorted according to value, which is the first element d[1. Reverse = True indicates that you need to flip, by default, from small to large, flip, that is, from big to small.

Sort the dictionary key (key):

The code is as follows:

DIC = {' A ':, ' BC ': 5, ' C ': 3, ' ASD ': 4, ' AA ': ",", ' d ': 0}

dict= Sorted (Dic.iteritems (), Key=lambda d:d[0]) # D[0] Indicates the key of the dictionary

Print Dict

#sorted中第三个可选参数为reverse, true means sorting from large to small

#默认reverse = False

6. Subclasses and Parent classes

The subclass constructor calls the initialization constructor of the parent class

The code is as follows:

Class A (object):

def __init__ (self):

Print "Testa

Class B (A):

def __init__ (self):

A.__init__ (self)

Subclass calls a function of the parent class with the same name

The code is as follows:

Super (). Fuleifunction ()

7. More flexible mode of parameter transfer

The code is as follows:

Func2 (A=1, b=2, c=3) #默认参数

FUNC3 (*args) #接受任意数量的参数, introduced in a tuple manner

Func4 (**kargs) #把参数以键值对字典的形式传入

Precede the variable with an asterisk prefix (*), which is stored in a tuple () object and assigned to the formal parameter. Within a function, when you need to process a parameter, you can do so simply by manipulating the formal parameters of this tuple type (here is args). Therefore, when a function is defined, it does not need to specify the number of parameters to handle any number of parameters.

The code is as follows:

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

Python's medium parameters can be combined in a variety of ways, and in mixed use, first pay attention to the way the function is written, you must observe:

1. A formal parameter (arg=) with a default value is required after a formal parameter (ARG) without a default value

2. The tuple parameter (*args) must be after a formal parameter (arg=) with a default value

3. The dictionary parameter (**kargs) must be after the tuple parameter (*args)

When a function is invoked, the parameters are passed as follows:

1. Assign an argument without a specified parameter to the formal parameter in order

2. Assign the arguments of the specified parameter name (ARG=V) to the corresponding formal parameter

3. Package the extra arguments without the specified parameters into a tuple pass to the tuple parameter (*args)

4. Package the extra arguments for the specified parameter name into a dict pass to the dictionary parameter (**kargs)

8. Lambda expression

Lambda expressions can be viewed as an anonymous function

Syntax format for lambda expressions:

Lambda parameter list: expression #参数列表周围没有括号, there is no return keyword or function name before returning a value

Copy code code as follows:

DEF fn (x):

return Lambda y:x + y

#调用

A = FN (2)

Print a (3)

#输出

5

Analysis

: After the FN (2) call, the equivalent of a = lambda Y:2 + y, then a (3) is invoked.

Equivalent to print lambda Y:2 + 3

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.