This article mainly introduces the basic operations of Python list, dictionary, and string. This article summarizes the most basic and commonly used operations, for more information, see create a list.
The code is as follows:
Sample_list = ['A', 1, ('A', 'B')]
Python list operations
The code is as follows:
Sample_list = ['A', 'B', 0, 1, 3]
Obtain a value in the list.
The code is as follows:
Value_start = sample_list [0]
End_value = sample_list [-1]
Delete the first value of the list
The code is as follows:
Del sample_list [0]
Insert a value to the list
The code is as follows:
Sample_list [0: 0] = ['sample value']
Returns the length of the list.
The code is as follows:
List_length = len (sample_list)
List traversal
The code is as follows:
For element in sample_list:
Print 'element'
Python list advanced operations/Tips
Generate a list of numerical increments
The code is as follows:
Num_inc_list = range (30)
# Will return a list [0, 1, 2,..., 29]
Initialize the list with a fixed value
The 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 types
1. list: list (dynamic array, vector of the C ++ standard library, but different types of elements can be included in a list)
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
The 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
The 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
The 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
A [1:] # fragment operator for sublist extraction
[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
The code is as follows:
L1 = L # The alias where 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
[ For k in L if ]
2. dictionary: dictionary (that is, map of the C ++ Standard Library)
The 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
The 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 () # return the value in the dictionary in the form of a list. the returned value list can contain duplicate elements.
D. items () # return all Dictionary items in the list. each item in the list comes from (key, value), but there is no special order for the items to be returned.
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
Dict1 = dict # alias
Dict2 = dict. copy () # clone, that is, another copy.
3. tuple: tuples (I .e. constant arrays)
The 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)
The code is as follows:
Str = "Hello My friend"
The string is a whole. It is impossible to directly modify a part of a string. But we can read a part of the string.
Substring extraction
The code is as follows:
Str [: 6]
String containing judgment operators: in, not in
The code is as follows:
"He" in str
"She" not in str
The string Module also provides many methods, such
The 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
The code is as follows:
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
The code is as follows:
Float (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-type integer number. 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)
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
Tuple (ls)
List (ls)