第二章 列表(数组)

1 列表概念

bicycle = ['trek','cannondale','redline','specialized']
print(bicycle)
#输出打印结果:
['trek', 'cannondale', 'redline', 'specialized']
1.1 通过索引下标打印指定位置的列表元素
print(bicycle[0]
#输出打印结果:
trek

注意:索引从0开始

常用拓展:1.访问最后一个元素(倒数第一个)

print(bicycle[-1])
#输出结果
specialized

同理:索引-2返回倒数第二个列表元素, 索引-3返回倒数第三个列表元素,以此类推。

1.2 修改、添加、删除元素。

1.2.1 修改列表中指定位置的元素
motorcycles[0] = 'ducati'
1.2.2 在文件末尾添加元素 append(元素名称)
 motorcycles.append('ducati')

​ 创建一个空列表

motorcycles = []
1.2.4 插入元素
 motorcycles.insert(0, 'ducati')

解释:方法insert()在索引0处添加空间, 并将值'ducati'存储到这个地方。这种操作将列表中既有的每个元素都右 移一个位置。

1.2.5 删除列表中的元素

1.使用del语句删除(知道要删除的元素在列表中的位置--索引

 del motorcycles[0]

2.使用pop()删除元素

​ (1) 删除末尾元素(可以接着使用它)

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles) 
 popped_motorcycle = motorcycles.pop() 
 print(motorcycles) 
 print(popped_motorcle)
#输出结果:
['honda', 'yamaha', 'suzuki'] 
['honda', 'yamaha'] 
suzuki

​ (2)删除列表中任何位置的元素(pop(元素索引))

motorcycles = ['honda', 'yamaha', 'suzuki'] 
first_owned = motorcycles.pop(0) 
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
#输出结果:
The first motorcycle I owned was a Honda.

3. del和pop()的使用不同之处

如果你要从列表 中删除一个元素,且不再以任何方式使用它,就使用del语句;

如果你要在删除元素后还能继续 使用它,就使用方法pop();(用del,无法进行进一步赋值使用)

口头禅:不”用“del,“用”pop

4. 根据”值“来删除元素--remove()

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
print(motorcycles) 
motorcycles.remove('ducati') 
print(motorcycles)
#输出结果['honda', 'yamaha', 'suzuki', 'ducati'] 
['honda', 'yamaha', 'suzuki']

注意:方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要

​ 使用循环来判断是否删除了所有这样的值。

1.3 组织列表

1.使用方法 sort()对列表进行永久性排序--相当于原来的列表顺序被覆盖(再也无法恢复到原来顺序)

#1  按字母顺序排列
cars = ['bmw', 'audi', 'toyota', 'subaru'] 
cars.sort()
print(cars)
#输出结果
['audi', 'bmw', 'subaru', 'toyota']
#2  与字母顺序相反的顺序排列-- sort(reverse=True)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True) 
print(cars)
#输出结果
['toyota', 'subaru', 'bmw', 'audi']

2.–使用函数 sorted()对列表进行临时排序

以特定的顺序呈现它们,可使用函数sorted(),同时不影响它们在列表中的原始排列顺序

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']

如果你要按与字母顺 序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True

sorted(reverse=True)----相当于java中的Arrays.sort();

3. 翻转打印列表(要反转列表元素的排列顺序)

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
print(cars) 
cars.reverse() 
print(cars)
#输出结果
['bmw', 'audi', 'toyota', 'subaru'] 
['subaru', 'toyota', 'audi', 'bmw']

4. 确定列表长度(len())

 cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)

注意:Python计算列表元素数时从1开始

特殊情况注意:仅当列表为空时,这种访问最后一个元素的方式才会导致错误:

motorcycles = []

print(motorcycles[-1])

2. 操作列表

2.1 遍历整个列表

​ 需要对列表中的每个元素都执行相同的操 作时,可使用Python中的for循环。

1565944480175.png

类似于java中的for-each循环

for(inti:array){}

命名规范使用单数和复数式名称

1565944649330.png
2.2 通过缩进来说明for的范围
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")

由于两条print语句都缩进了,因此它们都将针对列表中的每位魔术师执行一次

#输出结果:
Alice, that was a great trick! 
I can't wait to see your next trick, Alice. 
David, that was a great trick! 
I can't wait to see your next trick, David. 

Carolina, that was a great trick! 
I can't wait to see your next trick, Carolina.

没有缩进带来的后果---范围识别错误

magicians = ['alice', 'david', 'carolina']
for magician in magicians: 
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!")

由于第三条 print语句没有缩进,因此只执行一次

Alice, that was a great trick! 
I can't wait to see your next trick, Alice. 
David, that was a great trick! 
I can't wait to see your next trick, David. 
Carolina, that was a great trick! 
I can't wait to see your next trick, Carolina. 

Thank you, everyone. That was a great magic show!
2.3 避免缩进错误

2.3.1 忘记缩进

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
print(magician)
#输出结果:
 File "magicians.py", line 3 
 print(magician) 
 ^ 
IndentationError: expected an indented block

2.3.2 忘记缩进额外的代码行

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
    print(magician.title() + ", that was a great trick!") 
print("I can't wait to see your next trick, " + magician.title() + ".\n")python
#输出结果:
Alice, that was a great trick! 
David, that was a great trick! 
Carolina, that was a great trick! 
I can't wait to see your next trick, Carolina.

2.3.3 不必要的缩进

message = "Hello Python world!" 
print(message)
#输出结果:
File "hello_world.py", line 2 
 print(message) 
 ^ 
IndentationError: unexpected indent

尤其是在for循环中

2.3.4 遗漏了冒号

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians 
     print(magician)
#导致语法错误
2.4 创建数值列表

2.4.1 使用函数 range() ------包前不包后

for value in range(1,5): 
     print(value)
#输出结果:
1 
2 
3 
4

​ 2.4.2 使用range()创建数字列表

  1. 将range()作为list的参数,输出将为一个数字列表

    numbers = list(range(1,6)) 
    print(numbers)
    #输出结果:
    [1, 2, 3, 4, 5]
    
    1. ​ 使用函数range()时,还可指定步长,下面的代码打印1~10内的偶数

      even_numbers = list(range(2,11,2)) 
      print(even_numbers)
      #结果:解释:函数range()从2开始数,然后不断地加2,直到达到或超过终值(11),因此
      输出如下
      [2, 4, 6, 8, 10]
      
      1. 将10个整数的平方放入一个列表中

        #简化前:
        squares = [] 
        for value in range(1,11): 
        square = value**2 
        squares.append(square) 
        print(squares)
        #简化后:
        squares = [] 
        for value in range(1,11): 
        squares.append(value**2)
        print(squares)
        

        输出结果:

        #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
        

        2.4.2 Python函数

        ​ max(), min(), sum()

         digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
        min(digits)
        0 
         max(digits)
        9 
        sum(digits)
        45
        
        
        2.5 列表解析--------(作用:减少编写的代码行数)

        example:使用列表解析求解1~10的平方

        squares = [value**2 for value in range(1,11)] 
        print(squares)
        #结果:
        [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
        
        
        2.6 使用“切片”(包前不包后)-----操作列表的部分
        2.6.1 指定切片区间

        ​ 要创建切片,可指定要使用的第一个元素和最后一个元素的索引。Python 在到达你指定的第 二个索引前面的元素后停止。

        players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
        print(players[0:3])
        #结果:
        ['charles', 'martina', 'michael']
        
        
        2.6.2 未指定第一个索引---将自动从列表开头开始
        未指定尾部索引---将自动从当前开始位置一直到列表结束
        players = ['charles', 'martina', 'michael', 'florence', 'eli']
        print(players[:4])
        print(players[2:])
        #结果:
        ['charles', 'martina', 'michael', 'florence']
        ['michael', 'florence', 'eli']
        
        
        2.6.3 负数索引返回离列表末尾相应距离的元素
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[-3:])
#结果:
['michael', 'florence', 'eli']

2.7 遍历切片

example:遍历前三名队员

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

2.8 复制列表----只能用“切片”

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])

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']

注意: 不能简单的将两个列表名进行复制

 friend_foods = my_foods   错错错!!!!

解释:这种语法实际上是让Python将新变量friend_foods关联到包含在my_foods中的列表,因此这两个

变量都指向同一个列表.

2.9 元组(不可变的列表--用于创建一系列不可修改的元素)
2.9.1 定义元组

​ 元组的 定义要用“()”

dimensions = (200, 50) 
dimensions[0] = 250
#
Traceback (most recent call last): 
 File "dimensions.py", line 3, in  
 dimensions[0] = 250 
TypeError: 'tuple' object does not support item assignment

违反了元组内元素不能修改的特性。

2.9.2 遍历元组--(同列表)
dimensions = (200, 50) 
for dimension in dimensions: 
 print(dimension)
 #结果:
 200
 50

2.9.3 修改元组变量
dimensions = (200, 50)
print("Original dimensions:") 
for dimension in dimensions: 
 print(dimension) 
dimensions = (400, 100)    #对对对 修改变量重新复制
print("\nModified dimensions:") 
for dimension in dimensions: 
 print(dimension)
#输出:
Original dimensions: 
200 
50 
Modified dimensions: 
400 
100

小小的格式补充:缩进用Tab健,4个字符,每行代码不超过80字符,注释不超过72字符。善用空格。

你可能感兴趣的:(第二章 列表(数组))