Python built-in data structure details, python data structure details

Source: Internet
Author: User
Tags python list

Python built-in data structure details, python data structure details

I. List)

List is a data structure in which a series of projects can be stored. List items must be separated by commas (,) and enclosed in a pair of brackets to indicate that this is a list. The following example shows some basic operations on the list:

# Define a list object class_list: class_list = ['Michael ', 'bob', 'tracy'] # obtain the length of a class_list print 'class have ', len (class_list ), 'students' # access The object print in The class_list 'the 3rd student in class is ', class_list [2] # Insert The object class_list.append ('pole') to The class_list ') # delete a project del class_list [0] # Sort class_list class_list.sort () # print 'these students are: ', for student in class_list: print student,

Output result:

Class have 3 students
The 3rd student in class is Tracy
These students are: Bob Paul Tracy

Note the following points about the above Code:

You can add any type of objects to class_list. That is to say, the items in a list do not have the same type. You can even insert a list to class_list.
The sorting function acts on itself rather than returning a copy, which is different from the string type because the string cannot be modified.
The end keyword parameter of the print function is used to specify the output after the input is complete. The default value is a line break. The above code replaces the line break with a space character.

Ii. Tuple)

Tuple is similar to list in terms of usage and concept. You can regard tuple as a read-only list. That is to say, once defined, tuple cannot be modified. Objects in tuple cannot be added or deleted.

Items in tuple should also be separated by commas and enclosed in parentheses to make the table a tuple. This parentheses are optional, that is, you can define a tuple in the following two ways:

T = 'Adam ', 'lisa', 'bart'
T = ('Adam ', 'lisa', 'bart ')
However, it does not save the habit of parentheses. In addition, when tuple has only one item, there must be a comma after the first item. In this case, t = ('Adam ',) should be defined as this ',). This seems to be an odd constraint, but without this comma, tuple defined without parentheses becomes t = 'Adam ', which is obviously ambiguous.

3. Dictionary)

A dictionary can be seen as a set of key-value pairs. The key must be unique, and each key is associated with a value. The key must be an unchangeable object (such as tuple, numeric, and string ). Note that the key-value pairs in the dictionary are not sorted in any way.

The definition of a dictionary should follow the format d = {key1: value1, key2: value2, key3: value3 }. Key-value pairs are separated by colons, and key-value pairs are separated by commas, and all key-value pairs are enclosed by braces. Some basic operations are as follows:

# Dictionary definition d = {'Adam ': 95, 'lisa': 85, 'bart': 59} # obtain the value print "Adam's score is" by using the key ", d ['Adam '] # delete a key-Value Pair del d ['bart'] # traverse the dictionary for name, score in d. items (): print '{0} is {1 }'. format (name, score) # Add a key-Value Pair d ['Paul '] = 72 # determine whether a key exists in the dictionary. You can also use if AB. has_key ('lisa ') if 'lisa' in d: print "Lisa's address is", d ['lisa ']

The output result is:

Adam's score is 95Lisa is 85Adam is 95Lisa's address is 85

Iv. Sequences)

The three built-in data structures described above are sequences, and index operations are a basic operation of sequences. Through subscript operations, you can directly access objects in the sequence. Although the subscript operation has been demonstrated above-the number subscript is used for the queue and metadata, and the keyword subscript is used for the dictionary.

The subscript of a sequence starts from 0. In the above example, only the subscript is a positive number. In fact, the subscript can also be a negative number, such as-1,-2,-3 .... Negative subscript indicates a position in the opposite direction. For example, class_list [-1] returns the first and last item of class_list.

The sequence not only supports negative subscripts but also double subscripts, which represent an interval. For example, class_list [0: 3] returns a subsequence copy from subscript 1 to subscript 3 in class_list. Note that this interval is a half-closed half-open interval. This operation is called slicing operation ). If the second subscript of the slice operation exceeds the range of the sequence, the slice operation ends at the end of the sequence. In the slice operation, both lower labels have default values. The first default value is 0, and the second value is the sequence length.

You can also provide the third parameter for the slice operation. The third parameter represents the step of the slice operation. Its default value is 1. The step represents the spacing between items. For example, name [] returns a subsequence consisting of 0, 3, 6, and 9 in the lower-left name.

5. Set)

A set is a collection of unordered simple objects. When you only care about whether an object exists in the aggregation, regardless of the order in which it exists or the number of occurrences, it is suitable to use the set. Basic functions: Determine whether a set is a member, whether a set is a subset of another set, and obtain the intersection of the two sets. Instance:

S = set (['Adam ', 'lisa', 'bart', 'Paul ']) # determine whether the object is in the set if 'bart' in s: print "Bart is in? ", 'Bart' in s # use the copy function to copy a setsc = s. copy () # Add the object SC to the set. add ('bill ') # Delete the object SC from the set. remove ('Adam ') # Calculate the intersection of the two sets. You can also use s. intersection (SC) print s & SC

Output result:

Bart is in ? Trueset(['Lisa', 'Paul', 'Bart'])

Articles you may be interested in:
  • Examples of python list and tuples
  • Example of how Python merges and sorts two ordered lists
  • Common Python Data Structures
  • Python filter function filter () uses a custom function to filter sequence instances
  • Set)
  • Python set type operation summary
  • List, Dictionary, tuples, and collection Data Structure in Python
  • Python has three built-in data structures: List, tuples, and dictionary.
  • Summary of set learning in Python
  • Detailed description of the advanced data structure in Python
  • How to calculate the average value of a sequence in python
  • Conversion of Python strings, tuples, lists, and dictionaries

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.