Detailed explanation of Python's built-in data structures
This article summarizes and introduces 5 built-in data structures in Python and operation examples. It is very detailed. Friends who need it can refer to it.
1. 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,
The output result is:
class has 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 the class_list, that is to say, it is not required to be in a list Items are of the same type. You can even insert a list into class_list.
The sorting function acts on itself rather than returning a copy, which is different from the string type because strings 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 viewed as a collection of key-value pairs. 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']
The output result is:
Adam's score is 95 Lisa is 85 Adam is 95 Lisa's address is 85
4. Sequences
The three types introduced above The built-in data structures 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
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
Output result:
Bart is in ? True set(['Lisa', 'Paul', 'Bart'])
Related recommendations:
The above is the detailed content of Detailed explanation of Python's built-in data structures. For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.