Python序列:列表list、元组tuple、range

您所在的位置:网站首页 python列表属于无序序列 Python序列:列表list、元组tuple、range

Python序列:列表list、元组tuple、range

2023-06-02 06:04| 来源: 网络整理| 查看: 265

有三种基本序列类型:list, tuple 和 range 对象。

列表是可以修改的,而元组不可以。元组可用作字典键。

序列的通用操作 索引 indexing

索引中所有元素的编号都是从0开始

# 索引 string1='string1' print(string1[0])

输出结果:s

最后的索引为-1

# 最后一个字符索引为-1 string1='string1' print(string1[-1])

输出结果:1

切片 slicing

切片来访问特定范围内的元素

切片操作有3个参数,第一索引,第二索引,步长

切片的数学关系:[第一索引,第二索引),第二索引不包含在切片内

# 切片的第一索引=0,第二索引7不包含在内=6,实际显示0-6,也就是[0,7) string1='string1' print(len(string1)) print(string1[0:len(string1)])

输出结果:7 输出结果:string1

如果切片开始于序列头,或结束于序列末尾时,可以省略。

# 切片索引的省略 string1='string1' print(string1[:]) # 头尾省略 print(string1[:len(string1)]) # 头省略 print(string1[0:]) # 尾省略 print(string1[3:5]) # 取[3,5),也就是3、4

显示结果:string1 显示结果:string1 显示结果:string1 显示结果:in

普通切片的步长省略,省略时,步长=1

# 带步长的切片 number=list(range(11)) print(number[0:11:2]) print(number[::2])

显示结果:[0, 2, 4, 6, 8, 10] 显示结果:[0, 2, 4, 6, 8, 10]

步长为负数时,第一个索引必须必第二个索引大

# 步长为负 number=list(range(11)) print(number[11::-2]) print(number[::-2])

显示结果:[10, 8, 6, 4, 2, 0] 显示结果:[10, 8, 6, 4, 2, 0]

赋值用切片是创建副本

# 赋值用切片是创建副本 number=list(range(11)) number1 = number numberCopy = number[:] number1[1] = 0 number1[2] = 0 print('number:',number) # 被number1操作改变 print('number1:',number1) # 被number1操作改变 print('numberCopy:',numberCopy) # 不被number1操作改变,number1操作前被切片复制

显示结果:[0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10] 显示结果:[0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10] 显示结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

给切片赋值

# 切片赋值 number = list(range(11)) number[1:3] = [0, 0] print('number:', number)

显示结果:number: [0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10]

序列的加法

一般而言,不能拼接不同类型的序列。

# 序列的相加 print([1,2,3]+[4,5,6]) print([1,2,3]+['4','5','6']) print([1,2,3]+'456') #错误,list和string不能相加

显示结果:[1, 2, 3, 4, 5, 6] 显示结果:[1, 2, 3, '4', '5', '6'] 显示结果:Traceback (most recent call last):  File "E:\PyCode\Python_Study\LsitDemo.py", line 36, in     print([1,2,3]+'456')TypeError: can only concatenate list (not "str") to list

序列的乘法 # 序列的乘法 list1 = [None]*5 print(list1)

显示结果:[None, None, None, None, None]

布尔运算 # 布尔运算 string1='string1' print('s in string1:','s' in string1) print('a in string1:','a' in string1)

显示结果:s in string1: True 显示结果:a in string1: False

列表list

列表是可变序列,通常用于存放同类项目的集合(其中精确的相似程度将根据应用而变化)。

class list([iterable])

可以用多种方式构建列表:

使用一对方括号来表示空列表: []

使用方括号,其中的项以逗号分隔: [a], [a, b, c]

使用列表推导式: [x for x in iterable]

使用类型的构造器: list() 或 list(iterable)

构造器将构造一个列表,其中的项与 iterable 中的项具有相同的的值与顺序。 iterable 可以是序列、支持迭代的容器或其它可迭代对象。 如果 iterable 已经是一个列表,将创建并返回其副本,类似于 iterable[:]。 例如,list('abc') 返回 ['a', 'b', 'c'] 而 list( (1, 2, 3) ) 返回 [1, 2, 3]。 如果没有给出参数,构造器将创建一个空列表 []。

初始化与赋值

# list初始化 list1=[] for s in 'myStringList': list1.append(s) print('list1:', list1) list2=[None]*10 print('list2:', list2)

显示结果:list1: ['m', 'y', 'S', 't', 'r', 'i', 'n', 'g', 'L', 'i', 's', 't'] 显示结果:list2: [None, None, None, None, None, None, None, None, None, None]

修改和删除list中的元素

# 修改和删除list元素 list1 = [] for s in 'myList1': list1.append(s) print('list1:', list1) list1[6]='2' print('修改后list1[6]:', list1) del list1[6] print('删除后list1[6]:', list1)

显示结果:list1: ['m', 'y', 'L', 'i', 's', 't', '1'] 显示结果:修改后list1[6]: ['m', 'y', 'L', 'i', 's', 't', '2'] 显示结果:删除后list1[6]: ['m', 'y', 'L', 'i', 's', 't']

方法:

list

# list函数 string1 = 'string' list1 = list(string1) # str转list print('list1:', list1) string2=''.join(list1) # list转str print('string2:', string2)

显示结果:list1: ['s', 't', 'r', 'i', 'n', 'g'] 显示结果:string2: string

append:将一个对象附加到list末尾

string1 = 'string' list1 = list(string1) # str转list print('list1:', list1) string2=''.join(list1) # list转str print('string2:', string2)

显示结果:list1: ['l', 'i', 's', 't', '1'] 显示结果:list2: ['l', 'i', 's', 't', '2'] 显示结果:list1: ['l', 'i', 's', 't', '1', 'l', 'i', 's', 't', '2']

clear:清空list

string1 = 'list1' list1 = list(string1) # str转list print('list1:', list1) print('list1.clear():', list1.clear())

显示结果:list1: ['l', 'i', 's', 't', '1'] 显示结果:list1.clear(): None

copy:复制list

string1 = 'list1' list1 = list(string1) # str转list print('list1:', list1) list2 = list1.copy() print('list2:', list2) list1[4] = '2' print('list1:', list1) print('list2:', list2) # 改变源列表,不是改变copy复制的列表

显示结果:list1: ['l', 'i', 's', 't', '1'] 显示结果:list2: ['l', 'i', 's', 't', '1'] 显示结果:list1: ['l', 'i', 's', 't', '2'] 显示结果:list2: ['l', 'i', 's', 't', '1']

count:计算指定元素在list中出现的次数

string1 = 'list111' list1 = list(string1) # str转list print("list1.count('1'):", list1.count('1'))

显示结果:list1.count('1'): 3

index:在list中查找指定值第一次出现的索引

list1 = [0, 1, 1, 3, 4, 1] print("list1.index(1):", list1.index(1)) # 查找1第一次出现的索引 print("list1.index(1, 2):", list1.index(1, 2)) # 查找从索引2开始1第一次出现的索引 print("list1.index(1, 3, 6):", list1.index(1, 3, 6)) # 查找从索引2开始到索引6,1第一次出现的索引

显示结果:list1.index(1): 1 显示结果:list1.index(1, 2): 2 显示结果:list1.index(1, 3, 6): 5

insert:将一个对象插入到list中

list1 = [10, 12, 14] list1.insert(1, 11) # 在索引1处出入11,原索引1的内容往后 print("list1 after list1.insert(1, 11):", list1) list1.insert(3, 13) # 在索引3处出入13,原索引3的内容往后 print("list1 after list1.insert(3, 13):", list1) list1.insert(5, 15) # 在索引5处出入15,原索引5的内容往后 print("list1 after list1.insert(5, 15):", list1)

显示结果:list1 after list1.insert(1, 11): [10, 11, 12, 14] 显示结果:list1 after list1.insert(3, 13): [10, 11, 12, 13, 14] 显示结果:list1 after list1.insert(5, 15): [10, 11, 12, 13, 14, 15]

pop:从列表中删除一个元素,末尾的元素为最后一个,并返回删除的元素

list1 = [0, 1, 2, 3, 4] print("list1.pop():", list1.pop()) # 删除并返回末尾的元素 list2 = [0, 1, 2, 3, 4] print("list2.pop(1):", list2.pop(1)) # 删除并返回索引1的元素 list3 = [0, 1, 2, 3, 4] print("list3.pop(-1):", list2.pop(-1)) # 删除并返回索引-1的元素,也就是末尾

显示结果:list1.pop(): 4 显示结果:list2.pop(1): 1 显示结果:list3.pop(-1): 4

remove:删除第一个指定值的元素

list1 = [0, 1, 2, 1, 2] list1.remove(1) # 删除第一个1,也就是list1[1] print("list1 after list1.remove(1):", list1)

显示结果:list1 after list1.remove(1): [0, 2, 1, 2]

reverse:反转list

list1 = [0, 1, 2, 3, 4] list1.reverse() print("list1 after list1.reverse():", list1)

显示结果:list1 after list1.reverse(): [4, 3, 2, 1, 0]

sort:就地排序list

list1 = [0, 3, 4, 2, 1] list1.sort() print("list1 after list1.sort():", list1)

显示结果:list1 after list1.sort(): [0, 1, 2, 3, 4]

list1 = [0, 3, 4, 2, 1] list1.sort(reverse=True) print("list1 after list1.sort():", list1)

显示结果:list1 after list1.sort(): [4, 3, 2, 1, 0]

list1 = "This is a test string from Andrew".split() print("list1 before list1.sort(key=str.lower):", list1) list1.sort(key=str.lower) print("list1 after list1.sort(key=str.lower):", list1)

显示结果:list1 before list1.sort(key=str.lower): ['This', 'is', 'a', 'test', 'string', 'from', 'Andrew'] 显示结果:list1 after list1.sort(key=str.lower): ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

元组tuple

元组是不可变序列,通常用于储存异构数据的多项集(例如由 enumerate() 内置函数所产生的二元组)。 元组也被用于需要同构数据的不可变序列的情况(例如允许存储到 set 或 dict 的实例)。

class tuple([iterable])

可以用多种方式构建元组:

使用一对圆括号来表示空元组: ()

使用一个后缀的逗号来表示单元组: a, 或 (a,)

使用以逗号分隔的多个项: a, b, c or (a, b, c)

使用内置的 tuple(): tuple() 或 tuple(iterable)

构造器将构造一个元组,其中的项与 iterable 中的项具有相同的值与顺序。 iterable 可以是序列、支持迭代的容器或其他可迭代对象。 如果 iterable 已经是一个元组,会不加改变地将其返回。 例如,tuple('abc') 返回 ('a', 'b', 'c') 而 tuple( [1, 2, 3] ) 返回 (1, 2, 3)。 如果没有给出参数,构造器将创建一个空元组 ()。

请注意决定生成元组的其实是逗号而不是圆括号。 圆括号只是可选的,生成空元组或需要避免语法歧义的情况除外。 例如,f(a, b, c) 是在调用函数时附带三个参数,而 f((a, b, c)) 则是在调用函数时附带一个三元组。

元组实现了所有 一般 序列的操作。

对于通过名称访问相比通过索引访问更清晰的异构数据多项集,collections.namedtuple() 可能是比简单元组对象更为合适的选择。

tuple1 = (1, 2, 3) print('tuple1 is tuple:', type(tuple1) is tuple) tuple2 = () print('tuple2 is tuple:', type(tuple2) is tuple) tuple3 = (1) print('tuple3 is tuple:', type(tuple3) is tuple) tuple4 = (1,) # 逗号至关重要 print('tuple4 is tuple:', type(tuple4) is tuple) tuple5 = tuple([1, 2, 3]) print('tuple5 is tuple:', type(tuple5) is tuple) tuple6 = tuple5[0:2] #元组的切片也是元组 print('tuple6 is tuple:', type(tuple6) is tuple)

显示结果:tuple1 is tuple: True 显示结果:tuple2 is tuple: True 显示结果:tuple3 is tuple: False 显示结果:tuple4 is tuple: True 显示结果:tuple5 is tuple: True 显示结果:tuple6 is tuple: True

Range

range 类型表示不可变的数字序列,通常用于在 for 循环中循环指定的次数。

range 类型相比常规 list 或 tuple 的优势在于一个 range 对象总是占用固定数量的(较小)内存,不论其所表示的范围有多大(因为它只保存了 start, stop 和 step 值,并会根据需要计算具体单项或子范围的值)。

class range(stop)

class range(start, stop[, step])

range构造函数的参数必须是整数(内置 int 或任何实现 __index__() 特殊方法的对象)。 如果省略 step 参数,则默认为 1。如果省略 start 参数,则默认为 0。如果 step 为零,则引发 ValueError。

如果 step 为正值,确定 range r 内容的公式为 r[i] = start + step*i 其中 i >= 0 且 r[i] = 0 且 r[i] > stop.

如果 r[0] 不符合值的限制条件,则该 range 对象为空。 range 对象确实支持负索引,但是会将其解读为从正索引所确定的序列的末尾开始索引。

元素绝对值大于 sys.maxsize 的 range 对象是被允许的,但某些特性 (例如 len()) 可能引发 OverflowError。

start

start 形参的值 (如果该形参未提供则为 0)

stop

stop 形参的值

step

step 形参的值 (如果该形参未提供则为 1)

r = range(0, 20, 4) print(list(r)) # output: [0, 4, 8, 12, 16] print(4 in r) # output: True print(5 in r) # output: False print(r[2]) # output: 8 print(r[-2]) # output: 12 print(list(r[:2])) # output: [0, 4]



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3