列表和元组

Python 列表(list):

1.序列介绍:

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 – 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

Python有6个序列的内置类型,但最常见的是列表和元组。

序列都可以进行的操作包括索引,切片,加,乘,检查成员。

此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。

 

Python:可变序列和不可变序列

​可变序列:列表、集合、字典  可以进行增删改操作,序列地址页不会发生变化

​不可变序列:元组、字符串   没有增删改操作

#可变序列:列表、字典、集合
list_1 = [10,20,30]
print(id(list_1))   #list_1的地址为:2927159489792
list_1.append(40)
print(id(list_1))   #list_1的地址为:2927159489792 改变了值,列表地址并没有改变

#不可变序列:字符串、元组
str_1 = "HelloWorld"
print(id(str_1))    #str_1的地址为:2244899454896
str_1 = str_1+"1"
print(id(str_1))    #str_1的地址为:2244900762928  改变了值,字符串地址也发生了变化

 

 

2.列表的概述:

列表是包含0个或者多个元素的有序序列,属于序列类型。

特点:

a.列表的长度和内容是可变的(可以自由的对列表中的元素进行,增加、删除或者替换)

b.列表没有长度限制

c.列表中的元素类型可以不同(可以是基本数据类型,也可以是列表、元组、字典、集合以及其他自定义类型的对象)

 

3.创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:

#创建列表方式一
list_0 = []  #空列表
list_1 = ['elephan','monkey','tiger']
list_2 = [1,2,3]
list_3 = [1,2.2,'tiger',True,list_1]   #列表可存储不同的数据类型

#创建列表方式二:使用list()内置函数  list(obj)函数将字符串、range()对象、元组等对象转换为列表。
list_4 = list("python")
list_5 = list([1,2,3,4,5])
list_6 = list((1,2,3))
list_7 = list(range(1,5,2))

4.列表的索引

#列表的索引
list_1 = [1,2.2,'tiger',True]
print(list_1[0])
print(list_1[3])
#print(list_1[4])  报错,超出列表的长度

5.列表的分片

#列表的分片
list_1 = [1,2.2,'tiger',True]
print(list_1[1:3])
print(list_1[0:3:2])
print(list_1[-1:0:-1])    #反向分片的时候,注意步长要为负数

6.列表的分片赋值

x = [1,2,3,4]
x[1] = 1    #替换下角标为1的索引
print(x)
x[2:] = 5,6 #从下角标为2的索引开始替换
print(x)
x[1:1] = [1,2,3,4,5,6,7]    #在变量索引为1的位置插入 “1,2,3,4,5,6,7”
print(x)

#运行结果
[1, 1, 3, 4]
[1, 1, 5, 6]
[1, 1, 2, 3, 4, 5, 6, 7, 1, 5, 6]

7.循环遍历列表

为了能有效地逐一输出列表中的数据,可以使用while和for循环来便利输出列表。

while循环遍历列表:

x = [1,2,3,4,5,6,7,8,9]
length = len(x)
i = 0
while i<length:
    print(x[i])
    i+=1

for循环遍历列表:

x = [1,2,3,4,5,6,7,8,9]
for n in x:
    print(n)

 

8.查找元素与计数

index(obj)方法:用于返回指定元素在列表中首次出现的位置,如果该元素不在列表中则抛出异常。

animal = ['elephant','monkey','snake','tiger',(1,2,3)]
print(animal.index((1,2,3))
print(animal.index("snake")) #print(animal.index("喵喵")) #找不到喵喵会抛出异常 x = input("请输入您要查找的动物") if x in animal: a = animal.index(x) #返回索引值 print('元素{0}在列表中的索引为:{1}'.format(x,a)) else: print("列表中不存在该元素")

 

count(obj)方法:统计指定元素在列表中出现的次数

x = [1,2,2,2,3,4,[1,2,3,4],(1,2),(1,2)]
a = x.count(2)
print(a)
b = x.count((1,2))
print(b)
#运行结果
3
2

 

 

9.列表增加元素:append(obj)方法  extend(seq)方法  insert(index,obj)方法

append(obj):在列表的末尾添加新的元素、对象

add_list = [0,1,2,3,4]
add_list.append(5)  #在末尾添加一个元素5
print(add_list)
add_list.append([6,7])  #在末尾添加一个列表对象[6,7]
print(add_list)
x = [8,9]
add_list.append(x)  #在末尾添加一个列表对象x
print(add_list)
#运行结果
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, [6, 7]]
[0, 1, 2, 3, 4, 5, [6, 7], [8, 9]]

 

extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表拓展原来的列表)

list_1 = [1,2,3]
list_2 = [4,5,6]
list_1.extend("python") #将序列python与list_1合并
print(list_1)
list_1.extend(list_2) #将list_2看作一个序列,将这个序列和list_1合并
print(list_1)

 

insert(index,obj):可以将指定的对象添加到指定位置

#insert()方法
number = [1,2,4,5]
number.insert(2,3)  #在索引为2的位置添加元素3
print(number)
number.insert(5,[6,7])  #在索引为5的位置添加对象[6,7]
print(number)
x = [8,9]
number.insert(6,x)  #在索引为6的位置添加对象x
print(number)
#运行结果
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, [6, 7]]
[1, 2, 3, 4, 5, [6, 7], [8, 9]]

 

10.列表删除元素:del命令  pop()方法  remove()方法

del命令:根据索引删除列表中的元素(删除一个或者多个)

number = [1,2,3,4,5,6,7,8,9]
del number[2]   #删除索引为2的元素
print(number)
del number[1:3] #分片删除索引1:3的元素
print(number)
del number[-1:0:-2] #分片删除索引-1:0:-2的元素
print(number)

 

pop([obj])方法:用于移除列表中的一个元素(默认最后一个),并且返回该元素的值 (删除一个)

number = [1,2,3,4,5,6,7,8,9]
print(number.pop())  #默认删除最后一个元素,并返回该元素的值
print(number)
print(number.pop(0) )  #删除索引为0的元素
print(number)

 

 remove(obj)方法:移除列表中某个值的第一个匹配项。

#使用remove方法删除列表x中的所有'abc'
x = ["123",'abc',"ABC",'python','abc']
while 'abc' in x:
    x.remove('abc')
print(x)
#运行结果
['123', 'ABC', 'python']

 

11.列表排序

reverse()方法:用于将列表中的元素反向存放(修改原列表值)。

x = [1,2,3,4]
x.reverse()
print(x)
#运行结果
[4, 3, 2, 1]

 

sort([key = None],[reverse = False])方法:用于对原列表进行排序(默认为升序排序),排序后的新列表会覆盖原列表

key:传递给key参数的是一个函数,它指定可迭代对象中的每一个元素来按照该函数进行排序

reverse: 表示是否反向排序,默认为False

# 这里先看一个不带key参数的sort()函数,大家很容易知道结果
li = [[1, 7], [1, 5], [2, 4], [1, 1]]
li.sort()
print(li)  
# [[1, 1], [1, 5], [1, 7], [2, 4]] 默认按照0维排序 再按照1维排序

def fun(li):
    return li[1]
# 这时将函数fun传递给参数key 得出结果
li.sort(key=fun)
print(li) # [[1, 1], [2, 4], [1, 5], [1, 7]]     
#是li中每个子元素的第二个数进行排序
#无参数排序
x = [1,2,3,4,5]
x.sort()
print(x)
#指定参数排序,长度,反向
x_1 = ['a','abc','abcd','ab']
x_1.sort(key=len,reverse=True)
print(x_1)

#运行结果
[1, 2, 3, 4, 5]
['abcd', 'abc', 'ab', 'a']

 

 sorted(iterable,[key = None],[reverse = False])  函数:排序方式与sort一样,但是sorted函数会返回一个新列表,对原列表不进行修改

iterable:表示可迭代对象,在这里就是列表名。

#无参数排序
x_1 = [1,5,2,3,4]
x_2 = sorted(x_1)
print(x_1)
print(x_2)
#指定参数排序 x_1 = ['a','abc','abcd','ab'] x_2 = sorted(x_1,key=len,reverse=True) print(x_1) print(x_2) #运行结果 [1, 5, 2, 3, 4] [1, 2, 3, 4, 5] ['a', 'abc', 'abcd', 'ab'] ['abcd', 'abc', 'ab', 'a']

 

Python 元组(tuple):

元组是不可变序列,所以增删改操作不能使用。

1.为什么要将元组设计成为不可变序列

  • 在多任务环境下,同时操作对象不需要加锁
  • 在程序中尽量使用不可变序列

注意:元组中存储的是对象的引用

  • 如果元组中存储的对象本身为不可变对象,则不能引用其他对象
  • 如果元组中存储的对象本身为可变对象,则可变对象的引用不可改变,但是数据可以
    tuple_1 = (10,[20,30],"string")
    print("1",tuple_1[0],type(tuple_1[0]),id(tuple_1[0]))
    print("2",tuple_1[1],type(tuple_1[1]),id(tuple_1[1]))
    print("3",tuple_1[2],type(tuple_1[2]),id(tuple_1[2]))
    #tuple_1[0] = 1
    #tuple_1[1] = 1       这三行代码报错,不能修改元组的值
    #tuple_1[2] = 1
    tuple_1[1].insert(2,40)  #使用list的方法修改list的值,但是列表的引用地址并没有改变
    print("4",tuple_1[1],type(tuple_1[1]),id(tuple_1[1]))
    #运行结果
    1 10 <class 'int'> 2698032015952
    2 [20, 30] <class 'list'> 2698040063232
    3 string <class 'str'> 2698040230832
    4 [20, 30, 40] <class 'list'> 2698040063232

     

2.创建元组

#方式一:直接使用()创建
tuple_1 = (1,2.2,"Python",True)
print(tuple_1)          #运行结果(1, 2.2, 'Python', True)
#()可以省略不写
tuple_1 = 1,2.22,"Python",True
print(tuple_1)          #运行结果(1, 2.22, 'Python', True)

#方式二:使用内置函数tuple(obj)函数将字符串、range()对象、元组等对象转换为元组
tuple_2 = tuple("python")
tuple_3 = tuple([1,2,3,4,5])
tuple_4 = tuple((1,2,3))
tuple_5 = tuple(range(1,5,2))
tuple_6 = tuple({"a":"张三",True:1})
print(tuple_2)      #运行结果('p', 'y', 't', 'h', 'o', 'n')        
print(tuple_3)      #运行结果(1, 2, 3, 4, 5)
print(tuple_4)      #运行结果(1, 2, 3)
print(tuple_5)      #运行结果(1, 3)
print(tuple_6)      #运行结果('a', True)

#注意:当元组的值,只包含一个元素的时候,一定要加入一个逗号
tuple_7 = (1,)
tuple_8 = (1)
tuple_9 = ("",)
tuple_10 = ("")
print(tuple_7)      #运行结果(1,)
print(tuple_8)      #运行结果1
print(tuple_9)      #运行结果('你',)
print(tuple_10)     #运行结果你

 

3.元组的遍历

tuple_1 = ('python','world',94)
#方法一:使用循环利用索引,获取全部元组的元素
i = 0
length = len(tuple_1)
while i<length:
    print(tuple_1[i])
    i += 1
#方法二
for x in tuple_1:
    print(x)

 

4.元组的内置函数  

  • 序列都会具备的三个函数: len()   max()  min()
  • tuple():功能:以一个序列为参数,并把它转换为元组,如果参数本身是元组,则原样返回该参数(参考上文元组的知识点2,创建元组)

 

Tags: