通常来说Python中任何值都是一个对象,因此任何类型(int、str、list…)都是一个类。而类就必然有它的方法或属性,我们要记下这么多类的所有方法显然是不可能的,对此本文介绍两个小技巧:
dir() :内置函数,用来查询一个类或者对象所有属性,比如>>> dir(list)。
help() :内置函数,用来查询具体的说明文档,比如>>> help(int)。
在上一篇的Python3的基本数据类型中,我们初步了解了list列表,也介绍了列表是Python 中使用最频繁的数据类型。本文将进一步深入学习列表的使用。
一、列表的方法:
list.append(x)
在列表的尾部添加一个项,等价于 a[len(a):] = [x]。
list.extend(L)
将给定的列表L接到当前列表后面,等价于 a[len(a):] = L。
list.insert(i, x)
在给定的位置 i 前插入项,例如:a.insert(0, x) 会在列表的头部插入,而 a.insert(len(a), x) 则等价于 a.append(x)。
list.remove(x)
移除列表中第一个值为 x 的项,没有的话会产生一个错误。
list.pop([i])
删除列表给定位置的项,并返回它。如果没指定索引,a.pop()移除并返回列表最后一项。(方括号表示可选)
list.clear()
删除列表中的所有项,相当于 del a[:]。
list.index(x)
返回列表中第一个值为 x 的项的索引。如果没有匹配的项, 则产生一个错误。
list.count(x)
返回列表中 x 出现的次数。
list.sort()
就地完成列表排序。
list.reverse()
就地完成列表项的翻转。
list.copy()
返回列表的一个浅拷贝,相当于a[:]。
二、列表当栈
List的方法使得其可以很方便地作为一个栈来使用。我们知道,栈的特点是最后进入的元素最先出来(即后入先出),用append()方法进行压栈,用不指定索引的pop()方法进行出栈。
示例代码如下:
stack = [] for x in range(1,6): stack.append(x) # 入栈 print('push', x, end=' ') print(stack) print('Now stack is', stack) while len(stack)>0: print('pop', stack.pop(), end=' ') # 出栈 print(stack)
三、列表当队列
列表还可以当作队列来使用,队列的特性是第一个加入的元素第一个取出来(即先入先出)。然而,把列表当队列使用效率并不高,因为从列表的尾部添加和弹出元素是很快的,而在列表的开头插入或弹出是比较慢的(因为所有元素都得移动一个位置)。
要实现一个队列, 使用标准库的collections.deque, 它被设计成在两端添加和弹出都很快。
示例代码如下:
from collections import deque queue = deque() # 创建空队列 for x in range(1,6): queue.append(x) # 入队 print('push', x, end=' ') print(list(queue)) print('Now queue is', list(queue)) while len(queue)>0: print('pop', queue.popleft(), end=' ') # 出队 print(list(queue))
四、列表推导式
列表推导式提供了从序列创建列表的简单途径。通常程序会对序列的每一个元素做些操作,并以其结果作为新列表的元素,或者根据指定的条件来创建子序列。
列表推导式的结构是:在一个方括号里,首先是一个表达式,随后是一个 for 子句,然后是零个或更多的 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。
示例代码如下:
squares = [x**2 for x in range(10)] # 推导式 print(squares) # 输出是[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] pairs = [(x, y) for x in [1,2,3] for y in [3,1,4] if x!=y] # 推导式 print(pairs) # 输出是[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
五、列表嵌套
Python中并没有二维数组的概念,但我们可以通过列表嵌套达到同样的目的。
mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
同样,我们可以使用推导式生成嵌套的列表:
mat = [[1,2,3], [4,5,6], [7,8,9]] new_mat = [ [row[i] for row in mat] for i in [0,1,2] ] # 嵌套 print(new_mat) # 输出[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
附:del语句
del语句可以通过给定索引(而不是值)来删除列表中的项,它与返回一个值的pop()方法不同。del语句也可以移除列表中的切片,或者清除整个列表 :
lst = [1,2,3,4,5,6,7,8,9] del lst[2] # 删除指定索引项 print(lst) del lst[2:5] # 删除切片 print(lst) del lst[:] # 删除整个列表 print(lst) del也可以用于删除变量实体: del lst
在删除变量实体之后引用 lst 的话会产生错误。

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...


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

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development 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.