Home Backend Development Python Tutorial Python3基础之list列表实例解析

Python3基础之list列表实例解析

Jun 06, 2016 am 11:32 AM
list python3 list Base

通常来说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)

Copy after login

三、列表当队列

列表还可以当作队列来使用,队列的特性是第一个加入的元素第一个取出来(即先入先出)。然而,把列表当队列使用效率并不高,因为从列表的尾部添加和弹出元素是很快的,而在列表的开头插入或弹出是比较慢的(因为所有元素都得移动一个位置)。
要实现一个队列, 使用标准库的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))

Copy after login

四、列表推导式

列表推导式提供了从序列创建列表的简单途径。通常程序会对序列的每一个元素做些操作,并以其结果作为新列表的元素,或者根据指定的条件来创建子序列。

列表推导式的结构是:在一个方括号里,首先是一个表达式,随后是一个 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)]

Copy after login

五、列表嵌套

Python中并没有二维数组的概念,但我们可以通过列表嵌套达到同样的目的。

mat = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
   ]

Copy after login

同样,我们可以使用推导式生成嵌套的列表:

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]]

Copy after login

附: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

Copy after login

在删除变量实体之后引用 lst 的话会产生错误。

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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 remove square brackets from a list using Python How to remove square brackets from a list using Python Sep 05, 2023 pm 07:05 PM

Python is a very useful software that can be used for many different purposes depending on the need. Python can be used in web development, data science, machine learning, and many other fields that require automation. It has many different features that help us perform these tasks. Python lists are one of the very useful features of Python. As the name suggests, a list contains all the data you wish to store. It is basically a set of different types of information. Different Ways to Remove Square Brackets Many times, users come across a situation where list items are displayed within square brackets. In this article, we'll detail how to remove these brackets to get a better view of your listing. One of the easiest ways to remove parentheses in strings and replacement functions is in

How to count the number of elements in a list using Python's count() function How to count the number of elements in a list using Python's count() function Nov 18, 2023 pm 02:53 PM

How to use Python's count() function to calculate the number of an element in a list requires specific code examples. As a powerful and easy-to-learn programming language, Python provides many built-in functions to handle different data structures. One of them is the count() function, which can be used to count the number of elements in a list. In this article, we will explain how to use the count() function in detail and provide specific code examples. The count() function is a built-in function of Python, used to calculate a certain

How to Make a Shopping List in the iOS 17 Reminders App on iPhone How to Make a Shopping List in the iOS 17 Reminders App on iPhone Sep 21, 2023 pm 06:41 PM

How to Make a GroceryList on iPhone in iOS17 Creating a GroceryList in the Reminders app is very simple. You just add a list and populate it with your items. The app automatically sorts your items into categories, and you can even work with your partner or flat partner to make a list of what you need to buy from the store. Here are the full steps to do this: Step 1: Turn on iCloud Reminders As strange as it sounds, Apple says you need to enable reminders from iCloud to create a GroceryList on iOS17. Here are the steps for it: Go to the Settings app on your iPhone and tap [your name]. Next, select i

How to create a grocery list: Use the Reminders app for iPhone How to create a grocery list: Use the Reminders app for iPhone Dec 01, 2023 pm 03:37 PM

In iOS 17, Apple added a handy little list feature to the Reminders app to help you when you're out shopping for groceries. Read on to learn how to use it and shorten your trip to the store. When you create a list using the new "Grocery" list type (named "Shopping" outside the US), you can enter a variety of food and groceries and have them automatically organized by category. This organization makes it easier to find what you need at the grocery store or while out shopping. Category types available in alerts include Produce, Bread & Cereals, Frozen Foods, Snacks & Candy, Meat, Dairy, Eggs & Cheese, Baked Goods, Baked Goods, Household Products, Personal Care & Wellness, and Wine, Beer & Spirits . The following is created in iOS17

Can we insert null value in Java list? Can we insert null value in Java list? Aug 20, 2023 pm 07:01 PM

SolutionYes,Wecaninsertnullvaluestoalisteasilyusingitsadd()method.IncaseofListimplementationdoesnotsupportnullthenitwillthrowNullPointerException.Syntaxbooleanadd(Ee) Appends the specified element to the end of this list. Type parameter E − The runtime type of the element. Parameter e − element to be appended to this list

What is the difference between Del and remove() on lists in Python? What is the difference between Del and remove() on lists in Python? Sep 12, 2023 pm 04:25 PM

Before discussing the differences, let us first understand what Del and Remove() are in Python lists. Del Keyword in Python List The del keyword in Python is used to delete one or more elements from a List. We can also delete all elements, i.e. delete the entire list. Example of using del keyword to delete elements from a Python list #CreateaListmyList=["Toyota","Benz","Audi","Bentley"]print("List="

Create multiple directories from a list using Python Create multiple directories from a list using Python Sep 08, 2023 am 08:21 AM

Python has become one of the most popular programming languages ​​for various applications due to its simplicity and versatility. Whether you are an experienced developer or just starting out on your coding journey, Python offers a wide range of features and libraries that make complex tasks manageable. In this article, we will explore a practical scenario where Python can help us by automating the process of creating multiple directories based on a list. By leveraging the power of Python's built-in modules and techniques, we can handle this task efficiently without the need for manual intervention. In this tutorial, we will delve into the problem of creating multiple directories and provide you with different ways to solve this problem using Python. By the end of this article, our goal is for you

Unable to display win7 wireless network list Unable to display win7 wireless network list Dec 22, 2023 am 08:07 AM

In order to facilitate many people's mobile work, many notebooks are equipped with wireless network functions, but some people's computers cannot display the WiFi list. Now I will bring you how to deal with this problem under win7 system. Let's take a look. Bar. The wireless network list cannot be displayed in win7 1. Right-click the network icon in the lower right corner of your computer, select "Open Network and Sharing Center", open it and then click "Change Adapter Settings" on the left 2. After opening, right-click the mouse to select the wireless network adapter, and select "Diagnosis" 3. Wait for diagnosis. If the system diagnoses a problem, fix it. 4. After the repair is completed, you can see the WiFi list.

See all articles