列表

通常方括号([])来表示列表,并用逗号来分隔其中的元素


1
2
3
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']

根据值删除元素使用remove方法

根据值删除元素使用remove方法


1
2
3
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles.remove('ducati')) # 删完值后返回none代表已删除
print(motorcycles) # 输出完成后的列表

remove()从列表中删除元素时接着使用它的值

1
2
3
4
5
6
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
too_expensive = 'ducati'
print(motorcycles) # 先输出原始列表
motorcycles.remove('ducati')
print(motorcycles)
print("我不喜欢所以我把",too_expensive,"删了")

访问列表元素

列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可 下面为访问列表元素语法 当请求获取列表元素 python只返回元素 不包括方方括号和引号


1
2
3
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
print(bicycles[0].title()) #使用title函数更加简洁

sorted()对列表进行临时排序

1
2
3
4
5
6
7
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)

sort()对列表进行永久性排序

1
2
3
4
5
6
7
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
>> ['audi', 'bmw', 'subaru', 'toyota']
cars.sort(reverse=True)
print(cars)
>> ['audi', 'bmw', 'subaru', 'toyota']

使用reverse函数反转列表

1
2
3
4
num = [1,9,2,5,12,1]
## [1, 12, 5, 2, 9, 1]
num.reverse()
print(num)

len()确定列表的长度

1
2
3
num = [1,9,2,5,12,1]
print(len(num))
>> 6

下面这段代码展示了从列表mmagicians取出一个名字并赋值给magican

1
2
3
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician,end=',')

使用单数或复数这些命名约定可以帮助判断代码处理的是单个列表元素还是整个列表

1
2
3
for cat in cats:
for dog in dogs:
for item in list_of_items:

在 for 循环中执行更多的操作

1
2
3
4
magicians = ['alice', 'david', 'carolina']  # 在代码行for magician in magicians后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次
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")

在 for 循环结束后执行一些操作


1
2
3
4
5
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!") # 在循环外打印

忘记缩进 python将提示 IndentationError: expected an indented block


1
2
3
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)

忘记缩进额外的代码行


1
2
3
4
5
6
7
8
9
10
11
12
# 有时候循环可能会正常运行但结果可能会出乎意料
# 试图在循环中执行多项任务,却忘记缩进其中的一些代码行时,就会出现这种情况
# 示例源码
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!") # 第九行忘记缩进
# 因第一行缩进所以未报错 没有未进入循环 所以只打印了一位魔术师
# 总结如果想自己的代码依次执行循环请缩进到for循环语句块内
# 这也是一个逻辑错误

下面是专门处理数字列表的函数

1
2
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 实为演示 具体可以计算成百上万个
print(min(digits), "\n" + str(max(digits)))

列表解析

1
2
3
4
# 列表解析让你只需编写一行代码
# 就能生成这样的列表 列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素
squares = [value ** 2 for value in range(1,11)]
print(squares)
  1. 首先指定一个描述性的列表名 指定一个左方括号,并定义一个表达式用于将值存储到列表
  2. 在这个表达式为value**2,它计算平方值再加上右方括号注意没有:
  3. 总结:for循环没有:将1~10提供给表达式value ** 2计算结果返回当前列表

要创建自己的列表解析,需要经过一定的练习,但能够熟练地创建常规列表后,你会发现这样做是完全值得的。当你觉得编写三四行代码来生成列表有点繁复时,就应考虑创建列表解析了

列表非常适合用于存储数字集合

range()函数步长


1
2
for i in range(1, 6): # 输出a~b-1的数字
print(i)

步长


1
2
even_numbers = list(range(2,11,2)) # 步长为中间数意为a 到 b-1间隔2步
print(even_numbers) # 从2开始加2达到11停止

range函数创建数字列表


1
2
num = list(range(1,6))  # list函数将int类型转成list
print(num)

range函数和for循环创建整数1-10的乘方


1
2
3
4
5
squares = []
for value in range(1,10):
square = value ** 2 # 进行乘方运算其中value变量包含整数1-11
squares.append(square) # 把刚刚运算的结果添加到列表
print(square,end=',') # 输出结果

方法二、使代码更加简洁


1
2
3
4
squares = []
for value in range(1,11): # range函数循环的值赋值给value
squares.append(value ** 2)
print(squares) # 在循环外输出列表得到计算结果

与range函数一样要创建切片,可指定要使用的第一个元素和最后一个元素的索引
Python在到达你指定的第二个索引前面的元素后停止 a~b-1

示例源码

1
2
3
4
5
players = ['charles', 'martina', 'michael', 'florence', 'eli']  # 一个运动队成员列表
print(players[0:3]) # 输出列表前三个元素
print(players[1:4]) # 在4-1处停止
print(players[:5]) # 未指定第一个索引默认从0开始
print(players[2:]) # 未指定第二个索引默认到最后

遍历切片

1
2
3
4
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("以下是我队的前三名队员:")
for player in players[:3]:
print(player.title(), end=',')

使用切片复制列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # 同时省略起始索引和终止索引

print("My favorite foods are:" + str(my_foods))
print("\nMy friend's favourite foods are:" + str(friend_foods))
为核实我和朋友有不同列表 下面每个列表添加一个喜欢的食物
my_foods.insert(0,"ice-cream")
friend_foods.append("sandwitch")

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)

不使用切片复制列表

这种语法实际上是让Python将新变量friend_foods关联到包含在my_foods中的列表
因此这两个变量都指向同一个列表 所以如果在任意列表添加元素那么这俩个列表都会出现这个元素


1
2
3
4
5
6
7
8
9
10
my_foods = ['pizza', 'falafel', 'carrot cake']

friend_foods = my_foods # 把列表引用赋值给了friend_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)

此处关于变量的探讨

当列表赋给一个变量时,实际上是将列表的“引用”赋给了该变量
引用是一个值 指向某些数据 列表引用是指向一个列表的值
变量包含对列表值的引用,而不是列表值本身
对于字符串和整数值,变量就包含了字符串或整数值。
变量在保存可变数据类型 如字典列表会进行引用/对不可变数据类型如 字符串整形元组会直接进行赋值
总而言之 变量在 可变数据类型赋值会引用 不可变数据类型直接保存本身

while循环的案例

使用while循环来处理字典

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在
一个变量中,以方便你使用

列表之间移动元素

1
2
3
4
5
6
7
8
9
10
11
12
unconfirmed_users = ['小李', '小强', '小王', '小文']  # 待验证的用户
confirmed_users = [] # 完成验证的用户

while unconfirmed_users: # while一下未验证用户
current_user = unconfirmed_users.pop() # 利用pop函数将返回值添加到确认的用户

print("即将验证的用户!" + current_user.title()) # 输出即将验证的用户
confirmed_users.append(current_user) # 将当前用户添加到验证用户

print("\n已确认以下用户")
for confirmed_user in confirmed_users: # 遍历完成用户的用户
print(confirmed_user.title()) # 输出完成验证的用户

删除包含特定值的列表元素

1
2
3
4
5
6
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets: # 当小猫在pets列表里
pets.remove('cat') # 不断地循环删除删除小猫
print(pets)

使用用户输入来填充字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
answers = {}

# 设置一个标志 作用于是否循环
sign = True

while sign:
name = input("\n你叫什么名字?")
answer = input("你想哪天去爬山?")

# 将回答存储在字典
answers[name] = answer

# 查看还有几个人需要调查
repeat = input("还有其他人嘛(yes/no)")
if repeat == 'no'
sign = False # 关闭循环

print("\n---结束---")
for name,answer in answers:
print(name + "想" + answer + "爬山")