Python List Operation

Source: Internet
Author: User
Tags python list

Create list
Sample_list = ['A', 1, ('A', 'B')]

Python list operations
Sample_list = ['A', 'B', 0, 1, 3]

Obtain a value in the list.
Value_start = sample_list [0]
End_value = sample_list [-1]

Delete the first value of the List
Del sample_list [0]

Insert a value to the list
Sample_list [0: 0] = ['sample value']

Returns the length of the list.
List_length = Len (sample_list)

List Traversal
For element in sample_list:
Print (element)

Python list Advanced Operations/Tips

Generate a list of numerical increments
Num_inc_list = range (30)
# Will return a list [0, 1, 2,..., 29]

Initialize the list with a fixed value
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
Len (list) # The length of list. Actually, this method calls the _ Len _ (Self) method of this object.

Create a continuous list
L = range () # That is, L = [,], excluding the last element
L = range (1, 10, 2) # That is, L = [1, 3, 5, 7, 9]

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
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
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
[<Expr1> for K in L if <expr2>]

2. dictionary: Dictionary (that is, map of the C ++ Standard Library)
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
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
Dict1 = dict # Alias
Dict2 = dict. Copy () # clone, that is, another copy.

3. tuple: tuples (I .e. constant arrays)
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)
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
STR [: 6]
String containing judgment operators: In, not in
"He" in Str
"She" not in Str

The string module also provides many methods, such
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
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) # returns a floating point number. Float ("1e-1") returns 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)

Create list
Sample_list = ['A', 1, ('A', 'B')]

Python list operations
Sample_list = ['A', 'B', 0, 1, 3]

Obtain a value in the list.
Value_start = sample_list [0]
End_value = sample_list [-1]

Delete the first value of the List
Del sample_list [0]

Insert a value to the list
Sample_list [0: 0] = ['sample value']

Returns the length of the list.
List_length = Len (sample_list)

List Traversal
For element in sample_list:
Print (element)

Python list Advanced Operations/Tips

Generate a list of numerical increments
Num_inc_list = range (30)
# Will return a list [0, 1, 2,..., 29]

Initialize the list with a fixed value
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
Len (list) # The length of list. Actually, this method calls the _ Len _ (Self) method of this object.

Create a continuous list
L = range () # That is, L = [,], excluding the last element
L = range (1, 10, 2) # That is, L = [1, 3, 5, 7, 9]

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
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
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
[<Expr1> for K in L if <expr2>]

2. dictionary: Dictionary (that is, map of the C ++ Standard Library)
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
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
Dict1 = dict # Alias
Dict2 = dict. Copy () # clone, that is, another copy.

3. tuple: tuples (I .e. constant arrays)
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)
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
STR [: 6]
String containing judgment operators: In, not in
"He" in Str
"She" not in Str

The string module also provides many methods, such
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
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) # returns a floating point number. Float ("1e-1") returns 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)

Create list
Sample_list = ['A', 1, ('A', 'B')]

Python list operations
Sample_list = ['A', 'B', 0, 1, 3]

Obtain a value in the list.
Value_start = sample_list [0]
End_value = sample_list [-1]

Delete the first value of the List
Del sample_list [0]

Insert a value to the list
Sample_list [0: 0] = ['sample value']

Returns the length of the list.
List_length = Len (sample_list)

List Traversal
For element in sample_list:
Print (element)

Python list Advanced Operations/Tips

Generate a list of numerical increments
Num_inc_list = range (30)
# Will return a list [0, 1, 2,..., 29]

Initialize the list with a fixed value
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
Len (list) # The length of list. Actually, this method calls the _ Len _ (Self) method of this object.

Create a continuous list
L = range () # That is, L = [,], excluding the last element
L = range (1, 10, 2) # That is, L = [1, 3, 5, 7, 9]

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
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
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
[<Expr1> for K in L if <expr2>]

2. dictionary: Dictionary (that is, map of the C ++ Standard Library)
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
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
Dict1 = dict # Alias
Dict2 = dict. Copy () # clone, that is, another copy.

3. tuple: tuples (I .e. constant arrays)
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)
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
STR [: 6]
String containing judgment operators: In, not in
"He" in Str
"She" not in Str

The string module also provides many methods, such
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
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) # returns a floating point number. Float ("1e-1") returns 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)

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.