Python list array usage instance parsing, pythonarray
This article describes in detail how to use the Python list array as an example. Share it with you for your reference. The details are as follows:
The list in Python is similar to the variable array (ArrayList) in C # and used for sequential storage structure.
Create list
Copy codeThe Code is as follows: sample_list = ['A', 1, ('A', 'B')]
Python list operations
Copy codeThe Code is as follows: sample_list = ['A', 'B', 0, 1, 3]
Obtain a value in the list.
Copy codeThe Code is as follows: value_start = sample_list [0]
End_value = sample_list [-1]
Delete the first value of the List
Copy codeThe Code is as follows: del sample_list [0]
Insert a value to the list
Copy codeThe Code is as follows: sample_list [0: 0] = ['sample value']
Returns the length of the list.
Copy codeThe Code is as follows: list_length = len (sample_list)
List Traversal
Copy codeThe Code is as follows: for element in sample_list:
Print (element)
Python list Advanced Operations/Tips
Generate a list of numerical increments
Copy codeThe Code is as follows: num_inc_list = range (30)
# Will return a list [0, 1, 2,..., 29]
Initialize the list with a fixed value
Copy codeThe Code is as follows: initial_value = 0
List_length = 5
Sample_list = [initial_value for I in range (10)]
Sample_list = [initial_value] * list_length
# Sample_list = [0, 0, 0, 0]
Appendix: python built-in type'
1. list: list (dynamic array, vector of the C ++ standard library, but different types of elements can be included in a list)
Copy codeThe Code is as follows: a = ["I", "you", "he", "she"] # The element can be of any type.
Subscript: reads and writes by subscript, and is processed as an array.
Starts with 0 and has a negative submark.
0: the first element,-1: The last element,
-Len: the first element, the last element of the len-1.
Number of elements in the list
Copy codeThe Code is as follows: len (list) # The length of list. Actually, this method calls the _ len _ (self) method of this object.
Create a continuous list
Copy codeThe Code is as follows: L = range () # That is, L = [,], excluding the last element
L = range (1, 10, 2) # That is, L = [1, 3, 5, 7, 9]
List Method
Copy codeThe Code is as follows: L. append (var) # append Element
L. insert (index, var)
L. pop (var) # Return the last element and delete it from the list
L. remove (var) # Delete this element that appears for the first time
L. count (var) # number of elements in the list
L. index (var) # position of the element. If no value exists, an exception is thrown.
L. extend (list) # append list, that is, merge list to L
L. sort () # sort
L. reverse () # reverse Order
List OPERATOR:, +, *, key word del
Copy codeThe Code is as follows: a [1:] # fragment operator, used to extract sub-lists
[1, 2] + [3, 4] # is [1, 2, 3, 4]. Same as extend ()
[2] * 4 # is [2, 2, 2]
Del L [1] # delete a specified Element
Del L [] # Delete elements in the specified subscript range
Copy list
Copy codeThe Code is as follows: L1 = L # the alias for L1 is L. in C, the pointer address is the same, and the L1 operation is the L operation. Function parameters are passed in this way.
L1 = L [:] # L1 is a clone of L, that is, another copy.
List comprehension
[<Expr1> for k in L if <expr2>]
2. dictionary: dictionary (that is, map of the C ++ Standard Library)
Copy codeThe Code is as follows: dict = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3': 'printer '}
Each element is pair, which contains two parts: key and value. Key is of the Integer or string type, and value is of any type.
The key is unique, and the dictionary only recognizes the last assigned key value.
Dictionary Method
Copy codeThe Code is as follows: D. get (key, 0) # Same as dict [key]. If no key is added, the default value is returned. [] If no, an exception is thrown.
D. has_key (key) # returns TRUE if the key is available; otherwise, FALSE
D. keys () # Return the dictionary Key List
D. values ()
D. items ()
D. update (dict2) # Add a merged dictionary
D. popitem () # obtain a pair and delete it from the dictionary. If it is null, an exception is thrown.
D. clear () # clear the dictionary, same as del dict
D. copy () # copy the dictionary
D. cmp (dict1, dict2) # Compare the dictionary (Priority: number of elements, key size, key value size)
# The first big returns 1, the small returns-1, the same returns 0
Dictionary Replication
Copy codeThe Code is as follows: dict1 = dict # Alias
Dict2 = dict. copy () # clone, that is, another copy.
3. tuple: tuples (I .e. constant arrays)
Copy codeThe Code is as follows: tuple = ('A', 'B', 'C', 'D', 'E ')
You can use [],: Operator of list to extract elements. The element cannot be directly modified.
4. string: string (a list of characters that cannot be modified)
Copy codeCode: str = "Hello My friend"
A string is an integer. It is impossible to directly modify a part of a string. But we can read a part of the string.
Substring Extraction
Copy codeCode: str [: 6]
String containing judgment operators: in, not in
Copy codeThe Code is as follows: "He" in str
"She" not in str
The string module also provides many methods, such
Copy codeThe Code is as follows: S. find (substring, [start [, end]) # searches for substrings in the specified range and returns the index value. Otherwise,-1 is returned.
S. rfind (substring, [start [, end]) # Reverse Lookup
S. index (substring, [start [, end]) # Same as find, but the ValueError is not found.
S. rindex (substring, [start [, end]) # reverse lookup as above
S. count (substring, [start [, end]) # returns the number of substrings found.
S. lowercase ()
S. capitalize () # uppercase letters
S. lower () # lower case
S. upper () # convert to uppercase
S. swapcase () # case-insensitive swap
S. split (str, '') # convert string to list and split with spaces
S. join (list, '') # convert list to string and connect with Space
Built-in functions for processing strings
Copy codeCode: len (str) # String Length
Cmp ("my friend", str) # string comparison. First, return 1
Max ('abcxyz') # Find the largest character in the string
Min ('abcxyz') # Find the smallest character in the string
String Conversion
Oat (str) # changes to a floating point number. The result of float ("1e-1") is 0.1.
Int (str) # converts it to an integer. int ("12") returns 12.
Int (str, base) # converts it to base-based integer. The result of int ("11", 2) is 2.
Long (str) # variable growth integer,
Long (str, base) # converts it to a base hexadecimal long integer,
Character string formatting (note that most escape characters, such as C language, are omitted)
Copy codeThe Code is as follows: str_format % (parameter list) # The parameter list is defined in the form of tuple, that is, it cannot be changed during running.
>>> Print "" % s's height is % dcm "% (" My brother ", 180)
# The result is displayed as My brother's height is 180.
Mutual conversion between list and tuple
Copy codeThe Code is as follows: tuple (ls)
List (ls)
Python removes repeated elements from the List
Copy codeThe Code is as follows: a = [3, 3, 5, 7, 7, 5, 4, 2]
A = list (set (a) # [2, 3, 4, 5, 7] are all sorted.
I hope this article will help you with Python programming.
Processing of arrays in python Arrays
#1. sort by the second item of its neutron array:
>>> A. sort (key = lambda x: x [1])
>>>
[4, 0], [3, 1], [1, 2]
>>>
#2. Split the array.
>>> B = []
>>> Map (B. extend,)
[None, None, None]
>>> B
[4, 0, 3, 1, 1, 2]
>>>
# Integrated function:
>>> Def procArray ():
... B = []
... Map (B. extend, sorted (a, key = lambda (x: x [1])
... Return B
...
>>> Print procArray ([[1, 2], [3, 1], [4, 0])
[4, 0, 3, 1, 1, 2]
>>>
After learning python arrays (list) and dictionaries (dict), I feel that it is not convenient to operate arrays in PHP. I have not found a solution yet?
Alas, I don't know what to say about you. Can you read the contents...
I'm too lazy to answer you
Search the list by yourself. How can I perform dictionary operations?
List Method
L. append (var) # append Element
L. insert (index, var)
L. pop (var)
# Return the last element and delete it from the list
L. remove (var) # Delete this element that appears for the first time
L. count (var)
# Number of elements in the list
L. index (var) # position of the element. If no value exists, an exception is thrown.
L. extend (list)
# Append list, that is, merge list to L
L. sort () # sort
L. reverse () # reverse Order
Dictionary Method
D. get (key, 0)
# Same as dict [key]. If no key is added, the default value 0 is returned. [] If no, an exception is thrown.
D. has_key (key)
# If this key is available, TRUE is returned; otherwise, FALSE is returned.
D. keys () # Return the dictionary Key List
D. values ()
D. items ()
D. update (dict2) # Add a merged dictionary
D. popitem ()
# Obtain a pair and delete it from the dictionary. If it is null, an exception is thrown.
D. clear () # clear the dictionary, same as del dict
D. copy ()
# Copy a dictionary
D. cmp (dict1, dict2) # Compare the dictionary (Priority: number of elements, key size, key value size)
# The first big returns 1, the small returns-1, the same returns 0