python列表基础+进阶

python列表骚操作

python列表基础

首先当然是要说基础啦

  • List(列表) 是 Python 中使用最频繁的数据类型。
  • 列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。
  • 列表用” [ ] “标识,是 python 最通用的复合数据类型。
创建列表的几种方法
  • 默认方法
list1 = [0,1,2,3,4,5,6]
>>>list1
[0,1,2,3,4,5,6]
  • 使用range()函数
list2 = list(range(10))
>>>list2
[0,1,2,3,4,5,6,7,8,9]

list3 = list(range(5,10))
>>>list3
[5,6,7,8,9]

list4 = list(range(0,10,2)) #这里的"2"为步长
>>>list4
[0,2,4,6]
  • 列表生成式
a = [number for number in range(6)]
>>>a
[1,2,3,4,5]
  • 使用字符串创建列表
#按住字符串的个数分割列表包括空格等字符
a = list("123456")
>>>a
['1','2','3','4','5','6']

b = list("1,2,3,4")
>>>b
['1',',','2',',','3',',',4']
  • 使用元组创建列表
a = list((0,1,2,3,4,5,6))
>>>a
[0,1,2,3,4,5,6]
访问列表的几种方法
  • 指定位置访问列表元素
#注意列表的访问是从0开始
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
>>>print(bicycles[0])
trek

>>>print(bicycles[1])
cannondale

#访问位置从后边开始
>>>print(bicycles[-1])
specialized
  • 循环访问列表
    • 遍历整个列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician) 


alice
david
carolina
列表的修改
  • 指定位置直接修改
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
列表的添加
  • 使用append添加列表的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

#append是将添加的元素追加到列表的末尾
motorcycles.append('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
  • 使用insert()在指定位置插入元素
    • insert() 可在列表的任何位置添加新元素。为此,你需要指定新元素的索引和值。
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
['ducati', 'honda', 'yamaha', 'suzuki']
从列表中删除元素
  • 使用del语句删除元素
    • 使用 del 可删除任何位置处的列表元素,条件是知道其索引
    • 注意!:使用 del 语句将值从列表中删除后,你就无法再访问它了。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
  • 使用pop()删除元素

    • 方法 pop() 可删除列表末尾的元素,并让你能够接着使用它
    • 术语 弹出 ( pop )源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    popped_motorcycle = motorcycles.pop()
    print(motorcycles)
    print(popped_motorcycle)
    ['honda', 'yamaha', 'suzuki']
    ['honda', 'yamaha']
    suzuki
    • 术语 弹出 ( pop )源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素
    • 每当你使用 pop() 时,被弹出的元素就不再在列表中了
    • 如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用 del 语句;如果你要在删除元
      素后还能继续使用它,就使用方法 pop() 。
    motorcycles = ['honda', 'yamaha', 'suzuki']
    first_owned = motorcycles.pop(0)
    print('The first motorcycle I owned was a ' + first_owned + '.')  
    The first motorcycle I owned was a honda. 
  • 根据值删除元素

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
  • 使用 remove() 从列表中删除元素
    • 注意!:方法 remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive + " is too expensive for me.")
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
A Ducati is too expensive for me.

列表进阶

对列表进行操作的小方法
  • 使用方法 sort() 对列表进行永久性排序
#这里请注意sort()是必须吸先对列表进行排序才可以输出
#这里是按照首字母排序的
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
  • 你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向 sort() 方法传递参数 reverse=True
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
  • 使用函数 sorted() 对列表进行临时排序
    • 注意:这里的sorted()是临时的,并没有改变原来列表的结构。
    • 注意:sort()必须是先申明再进行输出而sorted()则可以直接在print()语句中使用
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
  • 倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
  • 确定列表的长度
 cars = ['bmw', 'audi', 'toyota', 'subaru']
 len(cars)

 4
列表的切片
  • 例子1
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])

['charles', 'martina', 'michael']
  • 例子2
    • 注意!:要切记列表的下标索引是从’0’开始的
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])

['martina', 'michael', 'florence']
  • 例子3
    • 如果你没有指定第一个索引, Python 将自动从列表开头开始:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])

['charles', 'martina', 'michael', 'florence']
  • 例子4
    • 要让切片终止于列表末尾,也可使用下边的格式
    • 注意!:这种格式是包括列表末尾元素的
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])

['michael', 'florence', 'eli']
  • 例子5
    • 如果你要输出名单上的最后三个元素
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])

['michael', 'florence', 'eli']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:-1])

['michael', 'florence']
  • 例子6
    • 这里的“2”为步长
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1::2])
['martina', 'florence']
遍历切片
  • 例子1
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())
Here are the first three players on my team:
Charles
Martina
Michael
列表的复制
  • 有一个列表,其中包含你最喜欢的四种食品,而你还想创建另一个列表,在其中包含一位朋友喜欢的所有食品。不过,你喜欢的食品,这位朋友都喜欢,因此你可以通过复制来创建这个列表
    • 在不指定任何索引的情况下从列表 my_foods 中提取一个切片,从而创建了这个列表的副本,再将该副本存储到变量 friend_foods
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
  • 给上边两个列表添加值
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
  • 倘若我们只是简单地将 my_foods 赋给 friend_foods ,就不能得到两个列表
my_foods = ['pizza', 'falafel', 'carrot cake']
# 这行不通
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
列表的深浅拷贝
  • 要了解拷贝就必须要知道可变类型和不可变类型

    • 不可变类型: 整型,浮点数,复数,布尔,字符串,元组
    • 可变类型:列表,字典。
  • 赋值:简单地拷贝对象的引用,两个对象的id相同。
    浅拷贝:创建一个新的组合对象,这个新对象与原对象共享内存中的子对象。
    深拷贝:创建一个新的组合对象,同时递归地拷贝所有子对象,新的组合对象与原对象没有任何关联。虽然实际上会共享不可变的子对象,但不影响它们的相互独立性。

    浅拷贝和深拷贝的不同仅仅是对组合对象来说,所谓的组合对象就是包含了其它对象的对象,如列表,类实例。而对于数字、字符串以及其它“原子”类型,没有拷贝一说,产生的都是原对象的引用。

  • 浅拷贝

    • 注意:浅拷贝和深拷贝的不同仅仅是对组合对象来说,所谓的组合对象就是包含了其它对象的对象,如列表,类实例。而对于数字、字符串以及其它“原子”类型,没有拷贝一说,产生的都是原对象的引用。
a = ['A', 'B', 'C']
b = list(a)
print(id(a), id(b))          # a和b身份不同
print()
for x, y in zip(a, b):       # 但它们包含的子对象身份相同
    print(id(a), id(b))
42617288 42618248

42617288 42618248
42617288 42618248
42617288 42618248
  • 深拷贝

    • 所谓“深拷贝”,是指创建一个新的对象,然后递归的拷贝原对象所包含的子对象。深拷贝出来的对象与原对象没有任何关联。
    • 深拷贝只有一种方式:copy模块中的deepcopy函数。
    import copy
    a = ['A', 'B', 'C']
    b = copy.deepcopy(a)
    print(id(a), id(b))
    print()
    for x, y in zip(a, b):
      print(id(x), id(y))
    41261064 41261256
    
    36352888 36352888
    40111552 40111552
    40111440 40111440
    • 为什么使用了深拷贝,a和b中元素的id还是一样呢?

    • 答:这是因为对于不可变对象,当需要一个新的对象时,python可能会返回已经存在的某个类型和值都一致的对象的引用。而且这种机制并不会影响 a 和 b 的相互独立性,因为当两个元素指向同一个不可变对象时,对其中一个赋值不会影响另外一个。

    我们可以用一个包含可变对象的列表来确切地展示“浅拷贝”与“深拷贝”的区别:

    import copy
    a = [[1, 2], [5, 6], [8, 9]]
    
    b = copy.copy(a)              # 浅拷贝得到b
    c = copy.deepcopy(a)          # 深拷贝得到c
    print(id(a), id(b))           # a 和 b 不同
    print()
    for x, y in zip(a, b):        # a 和 b 的子对象相同
      print(id(x), id(y))
    print()
    print(id(a), id(c))           # a 和 c 不同
    print()
    
    for x, y in zip(a, c):        #a 和 c 的子对象也不同
      print(id(x), id(y))
    print(id(x), id(y))
    37526920 37526856
    
    37525512 37525512
    37525704 37525704
    37526984 37526984
    
    37526920 37526792
    
    37525512 37526728
    37525704 37526600
    37526984 37526536
    37526984 37526536
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值