Python列表

2023-09-28 18

Python中,列表(list)是一种常用的复合数据类型,它是一种有序、可变、可重复的数据类型,用方括号[]表示,其中的元素可以是任意类型,包括整数、浮点数、字符串、布尔值等。列表可以包含多个元素,并且每个元素可以通过索引访问。本教程将介绍列表的基本操作,包括索引、切片、合并以及列表的增删等。

一、创建和访问列表

列表是用方括号标注,逗号分隔的一组值,可以包含不同类型的元素,但一般情况下,各个元素的类型相同:

>>>squares = [1, 4, 9, 16, 25]
>>>squares
[1, 4, 9, 16, 25]

和字符串(及其他内置 sequence 类型)一样,列表也支持索引和切片:

>>>squares[0] # indexing returns the item
1
>>>squares[-1]
25
>>>squares[-3:] # slicing returns a new list
[9, 16, 25]

切片操作返回包含请求元素的新列表。以下切片操作会返回列表的浅拷贝:

>>>squares[:]
[1, 4, 9, 16, 25]

二、列表的操作

1、合并列表

列表支持合并操作:

>>>squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2、列表修改

与 immutable 字符串不同,列表是 mutable 类型,其内容可以改变:

>>>cubes = [1, 8, 27, 65, 125] # something's wrong here
>>>4 ** 3 # the cube of 4 is 64, not 65!
64
>>>cubes[3] = 64 # replace the wrong value
>>>cubes
[1, 8, 27, 64, 125]

3、列表添加和删除

可以使用append()方法在列表末尾添加新元素:

>>>cubes.append(216) # add the cube of 6
>>>cubes.append(7 ** 3) # and the cube of 7
>>>cubes
[1, 8, 27, 64, 125, 216, 343]

为切片赋值可以改变列表大小,甚至清空整个列表:

>>>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>>letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>># replace some values
>>>letters[2:5] = ['C', 'D', 'E']
>>>letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>># now remove them
>>>letters[2:5] = []
>>>letters
['a', 'b', 'f', 'g']
>>># clear the list by replacing all the elements with an empty list
>>>letters[:] = []
>>>letters
[]

4、 获取列表长度

使用内置函数len()可以获取列表的长度。

>>>letters = ['a', 'b', 'c', 'd']
>>>len(letters)
4

三、嵌套列表

Python还可以创建包含其他列表的列表,形成嵌套结构:

>>>a = ['a', 'b', 'c']
>>>n = [1, 2, 3]
>>>x = [a, n]
>>>x
[['a', 'b', 'c'], [1, 2, 3]]
>>>x[0]
['a', 'b', 'c']
>>>x[0][1]
'b'
  • 广告合作

  • QQ群号:707632017

温馨提示:
1、本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。邮箱:2942802716#qq.com(#改为@)。 2、本站原创内容未经允许不得转裁,转载请注明出处“站长百科”和原文地址。
Python列表
上一篇: Python数字
Python列表
下一篇: Python元组