Home Backend Development Python Tutorial Detailed description of Python's built-in data structures

Detailed description of Python's built-in data structures

Mar 13, 2017 pm 06:08 PM

This article gives you a summary of the 5 built-in data structures and operation examples in Python. It is very detailed. Friends who need it can refer to it.

1. List (List)

list is a data structure in which a series of items can be stored. The items of the list need to be separated by commas and enclosed in a pair of square brackets to indicate that this is a list. The following example is used to show some basic operations of list:


# 定义一个 list 对象 class_list:
class_list = ['Michael', 'Bob', 'Tracy']
# 获得一个 class_list 的长度
print 'class have', len(class_list), 'students'
# 访问class_list中的对象
print 'The 3rd student in class is', class_list[2]
# 往 class_list 中插入对象
class_list.append('Paul')
# 从 class_list 中删除一个项目
del class_list[0]
# 对 class_list 进行排序
class_list.sort()
# 遍历整个class_list中的项目
print 'These students are :',
for student in class_list:
  print student,
Copy after login

The output result is:

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

There are a few things to note about the above code:

You can add any type of object to class_list, that is That said, items in a list are not required to be of the same type. You can even insert a list into class_list.
SortThe function acts on itself instead of 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 completed. The default is a newline character. The above code uses a space character to replace the newline character.

2. Tuple

tuple is not much different from list in usage and concept. Tuple can be regarded as a Read-only version of the list. This means that once a tuple is defined, it cannot be modified - objects cannot be added or deleted, nor can objects in the tuple be modified.

The items in the tuple should also be separated by commas, and the items should be enclosed in parentheses to indicate that they are a tuple. This parentheses are optional, which means that a tuple can be defined in the following two ways:

t = 'Adam', 'Lisa', 'Bart'
t = ('Adam', 'Lisa', 'Bart')
But omitting the pair of parentheses is not necessarily a good habit. In addition, when the tuple has only one item, there must be a comma after the first item. In this case, t = ('Adam',) should be defined like this. This may seem like an odd constraint, but without the comma, the tuple defined without parentheses becomes t = 'Adam', which is obviously ambiguous.

3. Dictionary

A dictionary can be regarded as a set of key-value (key-value) pairs gather. Keys must be unique, and each key is associated with a value. The key must be an immutable object (such as tuple, numeric type, string). Also note that the key-value pairs in the dictionary are not ordered in any way.

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


# 字典的定义
d = {
  'Adam': 95,
  'Lisa': 85,
  'Bart': 59
}
# 通过键来获取值
print "Adam's score is", d['Adam']
# 删除一个键值对
del d['Bart']
# 遍历字典
for name, score in d.items():
  print '{0} is {1}'.format(name, score)
# 往字典中增加一个键值对
d['Paul'] = 72
# 判断字典中是否存在某键,也可以用 if ab.has_key('Lisa')
if 'Lisa' in d:
  print "Lisa's address is", d['Lisa']
Copy after login

The output result is:


Adam's score is 95
Lisa is 85
Adam is 95
Lisa's address is 85
Copy after login

4. Sequences )

The three built-in data structures introduced above are all sequences, and the index operation is a basic operation of the sequence. The objects in the sequence can be accessed directly through the subscript operation. Although the subscripting operation has been demonstrated above - queues and tuples are subscripted with numbers, and dictionaries are subscripted with keywords.

The subscript of the 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 subscripts represent positions in the opposite direction. For example, class_list[-1] returns the last item in class_list.

The sequence not only supports negative subscripts but also double subscripts. This pair of double subscripts represents an interval. For example, class_list[0:3] returns a copy of the subsequence from subscript 1 to subscript 3 in class_list. Note that this interval is a pair of half-closed and half-open intervals. This operation is called a slicing operation. If the second index of the slicing operation exceeds the range of the sequence, the slicing operation will terminate at the end of the sequence. Both subscripts in the slicing operation have default values. The default value of the first is 0, and the size of the second is the length of the sequence.

You can also provide a third parameter for the slicing operation. The third parameter represents the step size of the slicing operation. Its default value is 1. The step size represents the distance between items, such as name[0:10:3]. What is returned is the subsequence composed of subscripts 0, 3, 6, and 9 in name.

5. Set (Set)

A collection is an unordered collection of simple objects. Sets are suitable when you only care about whether an object exists in a collection, regardless of the order in which it exists or the number of times it appears. Basic functions: determine whether it is a member of a set, whether a set is a subset of another set, obtain the intersection of two sets, etc. Example:


s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
# 判断对象是否在集合中
if 'Bart' in s:
  print "Bart is in ?", 'Bart' in s
# 使用copy函数来拷贝一个set
sc = s.copy()
# 往集合中添加对象
sc.add('Bill')
# 从集合中删除对象
sc.remove('Adam')
# 求两个集合的交集,也可以使用 s.intersection(sc)
print s & sc
Copy after login

Output result:


Bart is in ? True
set(['Lisa', 'Paul', 'Bart'])
Copy after login

The above is the detailed content of Detailed description of Python's built-in data structures. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in Python Introduction to Parallel and Concurrent Programming in Python Mar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in Python How to Implement Your Own Data Structure in Python Mar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and Deserialization of Python Objects: Part 1 Serialization and Deserialization of Python Objects: Part 1 Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Mathematical Modules in Python: Statistics Mathematical Modules in Python: Statistics Mar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

See all articles