Python list Operation usage summary, pythonlist

Source: Internet
Author: User
Tags python list

Python list Operation usage summary, pythonlist

This example describes the Python list Operation usage. We will share this with you for your reference. The details are as follows:

List is one of the basic data structures in python. It is similar to ArrayList in Java and supports the addition of dynamic elements. List also supports different types of elements in a List. list is an Object.

The most basic method to create a list
Copy codeThe Code is as follows: myList = ['A', 'B', 'C']

Common Python list operations are as follows:

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.

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

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 = 0list_length = 5sample_list = [ initial_value for i in range(10)]sample_list = [initial_value]*list_length# sample_list ==[0,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)
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

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. remove (var) # Delete the first element L. count (var) # The number of this element in the list. index (var) # position of the element. If no value exists, an exception is thrown. extend (list) # append list, that is, merge list to L. sort () # sort L. reverse () # reverse list OPERATOR:, +, *, keyword dela [1:] # fragment operator, used for sublist extraction [1, 2] + [3, 4] # [1, 2, 3, 3, 4]. Same as extend () [2] * 4 # [,] del L [1] # Delete the element del L [] # Delete the element 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. The function parameter is the clone of L1 = L [:] # L1 as L, that is, another copy.

Copy codeThe Code is as follows: 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

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 this key exists; otherwise, FALSED. 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 dictD. copy () # copy the dictionary D. cmp (dict1, dict2) # Compare the dictionary (priority is the number of elements, key size, key value size) # The first big return 1, small return-1, the same return 0

Dictionary Replication

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
"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, returns-1 s. rfind (substring, [start [, end]) # reverse lookup S. index (substring, [start [, end]) # Same as find, but the ValueError S is not found. rindex (substring, [start [, end]) # reverse lookup S. count (substring, [start [, end]) # returns the number of substring S. lowercase () S. capitalize () # uppercase S. lower () # convert to lowercase S. upper () # convert to uppercase S. swapcase () # case-insensitive S. split (str, '') # convert string to list and split S with spaces. 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 1max ('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, float ("1e-1") returns 0.1int (str) # changes to an integer, int ("12") returns 12int (str, base) # convert it to base-formatted integer. The result of int ("11", 2) is 2 long (str) # convert it to a growth integer, long (str, base) # convert to base-converted 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.
Copy codeThe Code is as follows: >>> 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)

Supplement:

In python, list is also an object, so it also has methods and attributes. You can use help (list) in the ptython interpreter to view its documentation. Some open methods are as follows:

Here is an example code to introduce the specific usage of these methods:

# Coding = UTF-8 # Filename: list. py # Date: 2012 11 20 # create a list method heatList = ['wade ', 'James', 'bosh', 'haslem'] tableList = list ('123 ') # The list method accepts the iterable parameter print 'miami heat has', len (heatList), 'nba Stars, they are: '# traverse the elements in the list for player in heatList: print player, # Add the heatList element to the list. append ('allen ') # Method 1: add the parameter objectprint' \ nAfter allen to the end of the list to join the team, they are: 'print heatListheatList. insert (4 ,' Lewis ') # Method 2: insert an element parameter 1: index location parameter 2: objectprint 'after lewis join the team, they are: 'print heatListheatList. extend (tableList) # method 3: extended list, parameter: iterable parameter print 'after extend a table list, now they are: 'print heatList # Delete element heatList from list. remove ('1') # Delete Method 1: If the parameter object has duplicate elements, only the top print "Remove '1 '.. now '1' is gone \ n ", heatListheatList. pop () # Delete Method 2: pop optional parameter index Delete the element at the specified position is the last element by default print "Pop the last eleme Nt '3' \ n ", heatListdel heatList [6] # Delete method 3: You can delete the specified element or list slice print" del '3' at the index 6 \ n ", heatList # logical judgment # statistical method count parameter: print 'James apears' and heatList of specific element values. count ('wade '), 'times' # in and not in print 'wade in list? ', ('Wade' in heatList) print 'wade not in list? ', ('Wade' not in heatList) # positioning index method: parameter: Value of a specific element optional parameter: Slice range print 'allen in the list? ', HeatList. index ('allen') # the Next line of code will report an error because allen is not in the top three # print 'allen in the fisrt 3 player? ', HeatList. index ('allen ',) # sort and reverse code print 'when the list is reversed: 'heatlist. reverse () print heatListprint 'when the list is sorted: 'heatlist. sort () # sort has three default parameters cmp = None, key = None, and reverse = False. Therefore, you can specify the sorting parameter and then talk about the partition of print heatList # list [start: end] The fragment does not contain the end element print 'Elements from 2nd to 3rd ', heatList []

I hope this article will help you with Python programming.

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.