python语法基础学习笔记Task03:列表与元组

1、列表(list)

  • 写在方括号之间、用逗号分隔开的数值列表
  • 列表内的项目不必全是相同的类型
  • list是一种有序的集合,可以随时添加和删除其中的元素
  • 列表的索引都是从0开始的

创建列表

  • 创建同类型列表
number = [2, 20200200.99]
print(number, type(number))
# [2, 20,200,200.99] <class 'list'>
  • 创建混合类型列表
 mix= [2, 'Hello',1.414,[5,15,20]]
print(mix, type(mix))
# [2, 'Hello',1.414,[5,15,20]]<class 'list'>
  • 创建空列表
empty = []
print(empty) 
# []

向列表添加元素

  • list.append(x)----在列表的末尾添加一个元素。相当于 a[len(a):] = [x]
fruits = ['orange','apple','pear','banana']
fruits.append('peach')
print(fruits)
#['orange','apple','pear','banana','peach']
fruits.append(['peach','grape'])
print(fruits)
#['orange','apple','pear','banana',['peach','grape']]
  • list.extend(iterable)----使用可迭代对象中的所有元素来扩展列表。相当于 a[len(a):] = iterable
fruits = ['orange','apple','pear','banana']
fruits.extend(['peach','grape'])
print(fruits)
#['orange','apple','pear','banana','peach','grape']
  • list.insert(i, x)----在给定的位置插入一个元素。第一个参数是要插入的元素的索引,所以 a.insert(0, x)插入列表头部,a.insert(len(a), x) 等同于 a.append(x)
fruits = ['orange','apple','pear','banana']
fruits.insert(0,'peach')
print(fruits)
#['peach','orange','apple','pear','banana']

删除列表中的元素

  • list.remove(x)----移除列表中第一个值为 x 的元素。如果没有这样的元素,则抛出 ValueError 异常。
fruits = ['orange','apple','pear','banana']
fruits.remove('apple')
print(fruits)
#['orange','pear','banana']
  • list.pop([i])----删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop() 将会删除并返回列表中的最后一个元素。
fruits = ['orange','apple','pear','banana']
fruits.pop()
print(fruits)
#banana
fruits.pop(0)
print(fruits)
#orange
fruits.pop(-1)
print(fruits)
#pear
  • list.clear()----删除列表中所有的元素。相当于 del a[:]
fruits = ['orange','apple','pear','banana']
fruits.clear()
print(fruits)
#[]

其他列表对象方法

  • list.count(x)----返回元素 x 在列表中出现的次数
fruits = ['orange','apple','apple','apple','pear','banana']
nums=fruits.count(apple)
print(nums)
#3
  • list.sort(key=None, reverse=False)----对列表中的元素进行排序(参数可用于自定义排序
list1 = [123, 456, 789, 567]
list1.sort()
print(list1)  # [123, 456, 567, 789]

list1.sort(reverse=True)
print(list1)  # [789, 567, 456, 123]
  • list.reverse()----反转列表中的元素
fruits = ['orange','apple','pear','banana']
fruits.reverse()
print(fruits)
#['banana','pear','apple','orange']
  • list.copy()----返回列表的一个拷贝。相当于 a[:]
fruits = ['orange','apple','pear','banana']
fruits.copy()
print(fruits)
#['orange','apple','pear','banana']
  • index(obj[, start[, end]])----从列表中找出某个值第一个匹配项的索引位置
list1 = [123, 456] * 5
print(list1.index(123))  # 0
print(list1.index(123, 1))  # 2
print(list1.index(123, 3, 7))  # 4

列表切片

格式:【start:end:step】
start:起始索引,从0开始,-1表示结束
end:结束索引
step:步长,end-start,步长为正时,从左向右取值。步长为负时,反向取值
注意:切片的结果不包含结束索引,即不包含最后的一位,-1代表列表的最后一个位置索引

a=[1,2,3,4,5,6]
b=a[:] #省略全部,代表截取全部内容,可以用来将一个列表拷给另一个列表
print(b)
#[1, 2, 3, 4, 5, 6]
c=a[0:-1:1] #从位置0开始到结束,每次增加1,截取。不包含结束索引位置
print(c)
#[1, 2, 3, 4, 5]
d=a[:3] #省略起始位置的索引,以及步长。默认起始位置从头开始,默认步长为1,结束位置索引为3
print(d)
#[1, 2, 3]
e=a[0:5:3] #从第一个位置到第6个位置,每3个取一个值
print(e)
#[1, 4]
f=a[5:0:-1] #反向取值
print(f)
#[6, 5, 4, 3, 2]
g=a[::-1]
print(g)
#[6, 5, 4, 3, 2, 1]

列表操作符

  • 比较操作符
    列表中有单个元素时,直接比较相对应的元素大小即可;列表中有多个元素时,首先从列表中的第0个位置的元素相比较大小,如果哪个列表的第0个位置的元素大,就认为该列表大。如果相等的话就一直比较下去,直到有一项大,就认为该列表大。
>>> list1 = [123]
>>> list2 = [456]
>>> list1 > list2
False
>>> list1 = [123,456]
>>> list2 = [456,123]
>>> list1 > list2
False
  • 逻辑操作符
>>> list3 = [123,456]
>>> (list1 < list2) and (list1 == list3)
True
  • 连接操作符(+)
    操作符“+”用于连接列表,不能连接不同的种类
>>> list4 = list1 + list2
>>> list4
[123, 456, 456, 123]  
  • 重复操作符(*)
>>> list1 * 3
[123, 456, 123, 456, 123, 456]
  • 列表作为栈使用
    列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用 append() 。要从堆栈顶部取出一个元素,使用 pop() ,不用指定索引
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
  • 列表作为队列使用
    列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。
    若要实现一个队列, collections.deque 被设计用于快速地从两端操作:
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

2、元组(tuple)

  • tuple一旦初始化就不能修改
  • 元组使用小括号,创建只需要在括号中添加元素,并使用逗号隔开即可

创建元祖

tup1 = (1, 2, 3, 4, 5 );#同类型元组
tup2 = 'a', 'b', 'c', 'd';#不带括号的
tup3 = ('Google', 'W3CSchool', 1997, 2000);#混合类型元组
tup4 = ();#空元组
tup5 = (50,);#只包含一个元素的元组,在后面要带逗号,否则括号会被当作运算符使用
nested = (1, 10.31, 'python'), ('data', 11)#二维元组
print(nested)
# ((1, 10.31, 'python'), ('data', 11))

访问元组

  • 元组可以使用下标索引来访问元组中的值(切片)
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])#tup1[0]: physics
print ("tup2[1:5]: ", tup2[1:5])#tup2[1:5]: (2, 3, 4, 5)

修改元组

  • 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
#创建一个新的元组
tup3 = tup1 + tup2
print(tup3)
#(12, 34.56, 'abc', 'xyz')
  • 元组中包含列表时,可以修改列表list中的元素
t = ('a', 'b', ['A', 'B'])#元组中的元素为'a','b','list'
t[2][0] = 'X'
t[2][1] = 'Y'
print(t)
#('a', 'b', ['X', 'Y']),'list'元素并没有改变

删除元组

  • 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组
tup = ('Google', 'W3CSchool', 1997, 2000)
print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)
#元组被删除后,输出变量会有异常信息
删除后的元组 tup : 
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (tup)
NameError: name 'tup' is not defined

元组运算符
在这里插入图片描述
元组索引截取

  • 元组也是一个序列,可以访问元组中的指定位置的元素,也可以截取索引中的一段元素
    在这里插入图片描述

元组内置函数
在这里插入图片描述
元组解压

  • 解压(unpack)一维元组(有几个元素左边括号定义几个变量)
t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python
  • 解压二维元组(按照元组里的元组结构来定义变量)
t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
  • 如果你只想要元组其中几个元素,用通配符「*」,英文叫 wildcard,在计算机语言中代表一个或多个元素。下例就是把多个元素丢给了 rest 变量。
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)  # 1 2 5
print(rest)  # [3, 4]
  • 如果你根本不在乎 rest 变量,那么就用通配符「*」加上下划线「_」
a, b, *_ = t
print(a, b)  # 1 2

参考文献

  • https://www.w3cschool.cn/python3/python3-tuple.html
  • https://www.liaoxuefeng.com/wiki/1016959663602400/1017092876846880
  • https://docs.python.org/zh-cn/3/tutorial/datastructures.html
  • https://www.runoob.com/python/python-tuples.html
  • https://mp.weixin.qq.com/s/p-HvNpmRkVFkwbyiuiuw8A
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值