Some common methods and techniques for Python collection

Source: Internet
Author: User
1. Three ways to reverse a string
1.1. Simulate methods in C + +, define an empty string to implement
By setting an empty string, and then iterating through the string in the argument from backward to forward, using the addition of the string to merge into the new string
Copy CodeThe 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 the Sectioning method
This is a feature in Python, the slice can take a negative value, this is the method of slicing, set the step to 1, so that the implementation of the reverse sort.
Copy CodeThe code is as follows:


def reverse_1 (text):
return Text[::-1]

1.3. Use the list

With the reverse method of the list, the text is converted to a list, then reversed by the reverse method, and then the string is concatenated through the join.
Copy the Code code as follows:


def reverse_2 (text):
temp = List (text)
Temp.reverse ()
Return '. Join (temp)


2. Using the reduce
Using anonymous functions and reduce ()
Copy CodeThe 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
Copy the Code code 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 to traverse the list
Copy CodeThe 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):
Print key//index is the index of the list


5. How to sort dictionaries
Dictionaries are sorted in the order of value values from large to small (default from small to sort).
Copy CodeThe 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 the output:
[(' AA ', ","), (' a ', +), (' BC ', 5), (' ASD ', 4), (' C ', 3), (' d ', 0)]

Now let's break down the code.
Print Dic.iteritems () gets a list of [(Key, value)].
Then, using the sorted method, the key parameter specifies that the sort is sorted by value, which is the d[1 of the first element. Reverse = True indicates that it needs to be flipped, the default is small to large, flip the words, that is, from large to small.
To sort the dictionary keys (key):
Copy the Code code as follows:


DIC = {' A ': +, ' BC ': 5, ' C ': 3, ' ASD ': 4, ' AA ': $, ' d ': 0}
dict= Sorted (Dic.iteritems (), Key=lambda d:d[0]) # D[0] represents the key of the dictionary
Print Dict
#sorted中第三个可选参数为reverse, True indicates a sort from large to small
#默认reverse = False

6. Subclasses and Parent classes
The subclass constructor calls the initialization constructor of the parent class
Copy the Code code as follows:


Class A (object):
def __init__ (self):
Print "TestA
Class B (A):
def __init__ (self):
A.__init__ (self)


A subclass calls a function with the same name as the parent class
Copy CodeThe code is as follows:


Super (). Fuleifunction ()


7. More flexible method of parameter transfer
Copy CodeThe code is as follows:


Func2 (A=1, b=2, c=3) #默认参数
FUNC3 (*args) #接受任意数量的参数, passed in as a tuple
Func4 (**kargs) #把参数以键值对字典的形式传入

Precede the variable with an asterisk prefix (*), and the arguments are stored in a tuple () object and assigned to the parameter. Inside the function, the parameter needs to be processed, as long as the formal parameter of the tuple type (here is args) is done. Therefore, the function does not need to specify the number of arguments when it is defined, it can handle the case of any number of arguments.

Copy the Code code as follows:


def calcsum (*args):
sum = 0
For i in args:
sum + = i
Print sum
#调用:
Calcsum (a)
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 parameters can be combined in a variety of forms, in the mixed use, first of all pay attention to the function of the wording, must abide by:

1. A formal parameter (arg=) with a default value must be followed by a formal parameter (ARG) without a default value
2. Tuple parameter (*args) must be after formal parameter (arg=) with default value
3. Dictionary parameters (**kargs) must be after the tuple parameter (*args)

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

1. Assigning arguments to parameters with no specified argument sequentially
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 passed to the tuple parameter (*args)
4. Package the arguments of the extra specified parameter name into a dict passed to the dictionary parameter (**kargs)

8. Lambda expression
Lambda expressions can be seen as an anonymous function
The syntax format for lambda expressions:
Lambda parameter list: expression #参数列表周围没有括号, no return keyword before returned value, no function name
Copy the Code code as follows:


DEF fn (x):
return Lambda y:x + y
#调用
A = FN (2)
Print a (3)
#输出
5

Analysis
: FN (2) is called after the equivalent of a = lambda Y:2 + y, and a (3) is tuned.
Equivalent to print lambda Y:2 + 3

  • Related Article

    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.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.