Python序列之list和tuple常用方法以及注意事项
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 "
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 "
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 "
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的常用方法以及注意事项。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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"

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(

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

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
