Home Backend Development Python Tutorial 跟老齐学Python之有容乃大的list(3)

跟老齐学Python之有容乃大的list(3)

Jun 06, 2016 am 11:33 AM

对list的操作

向list中插入一个元素

前面有一个向list中追加元素的方法,那个追加是且只能是将新元素添加在list的最后一个。如:

>>> all_users = ["qiwsir","github"]
>>> all_users.append("io")
>>> all_users
['qiwsir', 'github', 'io']
Copy after login

从这个操作,就可以说明list是可以随时改变的。这种改变的含义只它的大小即所容纳元素的个数以及元素内容,可以随时直接修改,而不用进行转换。这和str有着很大的不同。对于str,就不能进行字符的追加。请看官要注意比较,这也是str和list的重要区别。

与list.append(x)类似,list.insert(i,x)也是对list元素的增加。只不过是可以在任何位置增加一个元素。

我特别引导列为看官要通过官方文档来理解:

代码如下:


list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).


这次就不翻译了。如果看不懂英语,怎么了解贵国呢?一定要硬着头皮看英语,不仅能够学好程序,更能...(此处省略两千字)

根据官方文档的说明,我们做下面的实验,请看官从实验中理解:

>>> all_users
['qiwsir', 'github', 'io']
>>> all_users.insert("python")   #list.insert(i,x),要求有两个参数,少了就报错
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)

>>> all_users.insert(0,"python")
>>> all_users
['python', 'qiwsir', 'github', 'io']

>>> all_users.insert(1,"http://")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io']

>>> length = len(all_users)
>>> length
5

>>> all_users.insert(length,"algorithm")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']

Copy after login

小结:

list.insert(i,x),将新的元素x 插入到原list中的list[i]前面
如果i==len(list),意思是在后面追加,就等同于list.append(x)
删除list中的元素

list中的元素,不仅能增加,还能被删除。删除list元素的方法有两个,它们分别是:

list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
Copy after login

我这里讲授python,有一个习惯,就是用学习物理的方法。如果看官当初物理没有学好,那么一定是没有用这种方法,或者你的老师没有用这种教学法。这种方法就是:自己先实验,然后总结规律。

先实验list.remove(x),注意看上面的描述。这是一个能够删除list元素的方法,同时上面说明告诉我们,如果x没有在list中,会报错。

>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']
>>> all_users.remove("http://")
>>> all_users    #的确是把"http://"删除了
['python', 'qiwsir', 'github', 'io', 'algorithm']

>>> all_users.remove("tianchao")    #原list中没有“tianchao”,要删除,就报错。
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

Copy after login

注意两点:

如果正确删除,不会有任何反馈。没有消息就是好消息。
如果所删除的内容不在list中,就报错。注意阅读报错信息:x not in list
看官是不是想到一个问题?如果能够在删除之前,先判断一下这个元素是不是在list中,在就删,不在就不删,不是更智能吗?

如果看官想到这里,就是在编程的旅程上一进步。python的确让我们这么做。

>>> all_users
['python', 'qiwsir', 'github', 'io', 'algorithm']
>>> "python" in all_users    #这里用in来判断一个元素是否在list中,在则返回True,否则返回False
True

>>> if "python" in all_users:
...   all_users.remove("python")
...   print all_users
... else:
...   print "'python' is not in all_users"
... 
['qiwsir', 'github', 'io', 'algorithm']   #删除了"python"元素

>>> if "python" in all_users:
...   all_users.remove("python")
...   print all_users
... else:
...   print "'python' is not in all_users"
... 
'python' is not in all_users    #因为已经删除了,所以就没有了。

Copy after login

上述代码,就是两段小程序,我是在交互模式中运行的,相当于小实验。

另外一个删除list.pop([i])会怎么样呢?看看文档,做做实验。

>>> all_users
['qiwsir', 'github', 'io', 'algorithm']
>>> all_users.pop()   #list.pop([i]),圆括号里面是[i],表示这个序号是可选的
'algorithm'       #如果不写,就如同这个操作,默认删除最后一个,并且将该结果返回

>>> all_users
['qiwsir', 'github', 'io']

>>> all_users.pop(1)    #指定删除编号为1的元素"github"
'github'

>>> all_users
['qiwsir', 'io']
>>> all_users.pop()
'io'

>>> all_users      #只有一个元素了,该元素编号是0
['qiwsir']
>>> all_users.pop(1)  #但是非要删除编号为1的元素,结果报错。注意看报错信息
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: pop index out of range   #删除索引超出范围,就是1不在list的编号范围之内

Copy after login

给看官留下一个思考题,如果要向前面那样,能不能事先判断一下要删除的编号是不是在list的长度范围(用len(list)获取长度)以内?然后进行删除或者不删除操作。

list是一个有意思的东西,内涵丰富。看来下一讲还要继续讲list。并且可能会做一个有意思的游戏。请期待。

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 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
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 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

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

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

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

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python? How to Create Command-Line Interfaces (CLIs) with Python? Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

Scraping Webpages in Python With Beautiful Soup: Search and DOM Modification Scraping Webpages in Python With Beautiful Soup: Search and DOM Modification Mar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

See all articles