Home Backend Development Python Tutorial Python序列之list和tuple常用方法以及注意事项

Python序列之list和tuple常用方法以及注意事项

Jun 06, 2016 am 11:20 AM
list Common methods

sequence 序列

sequence(序列)是一组有顺序的对象的集合。序列可以包含一个或多个元素,也可以没有任何元素。

我们之前所说的基本数据类型,都可以作为序列的对象。对象还可以是另一个序列。序列有两种:list (表) 和 tuple(元组) 。
list和tuple的主要区别在于,一旦建立,tuple的各个元素不可再变更,而list的各个元素可以再变更。

List

获得list元素的个数:

代码如下:


>>> lst=['更新慢','python',5.44,False]
>>> len(lst)
4

引用访问时索引是从0开始,注意不要越界:

代码如下:


>>> lst[0]
'更新慢'
>>> lst[1]
'python'
>>> lst[2]
5.44
>>> lst[3]
False
>>> lst[4]
Traceback (most recent call last):
  File "", line 1, in
    lst[4]
IndexError: list index out of range

用-1做索引,直接获取最后一个元素:

代码如下:


>>> lst[-1]
False
>>> lst[-2]
5.44
>>> lst[-3]
'python'
>>> lst[-4]
'更新慢'
>>> lst[-5]
Traceback (most recent call last):
  File "", line 1, in
    lst[-5]
IndexError: list index out of range

因为list是一个可变的有序表,所以,可以往list末尾追加元素:

代码如下:


>>> lst.append('加我一个')
>>> lst
['更新慢', 'python', 5.44, False, '加我一个']

一次追加多个元素:

代码如下:


>>> lst.extend(['A','B','C'])
>>> lst
['更新慢', 'python', 5.44, False, '加我一个', 'A', 'B', 'C']

要删除list末尾的元素,用pop()方法:

代码如下:


>>> lst.pop()
'C'
>>> lst
['更新慢', 'python', 5.44, False, '加我一个', 'A', 'B']

删除指定位置的元素,用pop(i)方法,其中i是索引位置:

代码如下:


>>> lst.pop(0)
'更新慢'
>>> lst
['python', 5.44, False, '加我一个', 'A']

list元素替换,可以直接赋值给对应的索引位置:

代码如下:


>>> lst[-1]='100'
>>> lst
['python', 5.44, False, '加我一个', '100']

list元素也可以是另一个list,插入的那个list只算一个元素:

代码如下:


>>> lst.append(lst1)
>>> lst
['python', 5.44, False, '加我一个', '100', ['666', 'QWER']]
>>> len(lst)
6

Tuple

Tuple一旦初始化就不能修改。字符串是一种特殊的元素,因此可以执行元组的相关操作。

代码如下:


>>> str='该睡觉了,晚安!'
>>> print (str[:7])
该睡觉了,晚安

不可变的tuple意义就在于因为不可变,所以代码更安全。如果可能,能用tuple就尽量用tuple。

代码如下:


>>> tuple=('1','2','3')
>>> tuple[0]=6
Traceback (most recent call last):
  File "", line 1, in
    tuple[0]=6
TypeError: 'tuple' object does not support item assignment

定义一个空tuple:

代码如下:


>>> tuple1=()
>>> tuple1
()


注意,要定义一个只有1个元素的tuple:

代码如下:


>>> tuple2=(666,)
>>> tuple2
(666,)              #正确的
>>> tuple3=(666)
>>> tuple3
666                 #错误的,只定义了666这个数

注意:Tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。

代码如下:


>>> l=['CCTV-5','HI']
>>> tuple4=('UFO','HACK',l)
>>> tuple4
('UFO', 'HACK', ['CCTV-5', 'HI'])
>>> l[1]='我先变一下'
>>> tuple4
('UFO', 'HACK', ['CCTV-5', '我先变一下'])

所以尽量避免这种套用。

当日小结

掌握List和Tuple的常用方法以及注意事项。

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
1 months 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 implement Redis List operation in php How to implement Redis List operation in php May 26, 2023 am 11:51 AM

List operation //Insert a value from the head of the list. $ret=$redis->lPush('city','guangzhou');//Insert a value from the end of the list. $ret=$redis->rPush('city','guangzhou');//Get the elements in the specified range of the list. 0 represents the first element of the list, -1 represents the last element, and -2 represents the penultimate element. $ret=$redis->l

How to convert JSONArray to List in Java How to convert JSONArray to List in Java May 04, 2023 pm 05:25 PM

1: JSONArray to ListJSONArray string to List//Initialize JSONArrayJSONArrayarray=newJSONArray();array.add(0,"a");array.add(1,"b");array.add(2,"c") ;Listlist=JSONObject.parseArray(array.toJSONString(),String.class);System.out.println(list.to

How to sort a list using List.Sort function in C# How to sort a list using List.Sort function in C# Nov 17, 2023 am 10:58 AM

How to sort a list using the List.Sort function in C# In the C# programming language, we often need to sort the list. The Sort function of the List class is a powerful tool designed for this purpose. This article will introduce how to use the List.Sort function in C# to sort a list, and provide specific code examples to help readers better understand and apply this function. The List.Sort function is a member function of the List class, used to sort elements in the list. This function receives

What are the common methods of List in Java basics What are the common methods of List in Java basics May 14, 2023 am 10:16 AM

1. Introduction to List interface List is an ordered collection and a repeatable collection. It inherits the Collection interface. Repeated elements can appear in the List collection, and the element at the specified position can be accessed through the index (subscript). 2. List common methods - voidadd (intindex, Obejctelement) method 1. The voidadd (intindex, Obejctelement) method inserts the element element at the specified position and moves the subsequent element back one element. 2.voidadd(intindex,Obejctelemen

How to convert array to List in Java How to convert array to List in Java Apr 19, 2023 am 09:13 AM

1. The most common way (not necessarily the best) is through Arrays.asList(strArray). After converting the array into List, you cannot add or delete the List, you can only check and modify it, otherwise an exception will be thrown. Key code: Listlist=Arrays.asList(strArray);privatevoidtestArrayCastToListError(){String[]strArray=newString[2];Listlist=Arrays.asList(strArray);//Insert a piece of data into the converted list list.add(" 1&quot

Why doesn't list.sort() return a sorted list in Python? Why doesn't list.sort() return a sorted list in Python? Sep 18, 2023 am 09:29 AM

Example In this example, we first look at the usage of list.sort() before continuing. Here, we have created a list and sorted it in ascending order using sort() method - #CreatingaListmyList=["Jacob","Harry","Mark","Anthony"]#DisplayingtheListprint("List=",myList)#SorttheListsinAscendingOrdermyList .sort(

What is the difference between the set method and the add method in List in java? What is the difference between the set method and the add method in List in java? Apr 19, 2023 pm 07:49 PM

Preface There are two very similar methods in the commonly used collection interface List in Java: Eset(intindex,Eelement); voidadd(intindex,Eelement); both of these methods insert specified elements at specified positions in the collection, then What is the difference between these two methods? Next, let’s take a look at the differences and similarities between these two methods through ArrayList, our commonly used collection implementation. First, let’s take a look at the similarities between these two methods in ArrayList. They will insert new elements at specified positions in the collection, such as the following Example: #Insert an F in the 2nd position of the collection #Insert Listlist= through the add method

How to convert Json to List, Map and entity into each other in Java How to convert Json to List, Map and entity into each other in Java May 27, 2023 pm 12:07 PM

Step 1: Import dependency com.google.code.gsongson2.8.6 Step 2: Start using Scenario 1: Convert ordinary objects (Beans). 1. Converting ordinary JavaBeans to Json strings is the most commonly used operation. First, create a simple class, such as Person. publicclassPerson{privateStringname;privateintage;privatebooleanisMale;privateListhobbies;//Omit the constructor and getter/setter methods, pay attention to overriding the toString method for easy viewing and control

See all articles