Python自学笔记(1)

整理一下Python相关内容,方便查阅。

参考用书:《Python编程:从入门到实践》,作者:Eric Matthes

第1章 变量和简单数据类型

第一个Python程序:

print("Hello world!")

只有一行,作用是打印输出“Hello world!”,语句末尾不要用分号。值得注意的是,print()函数打印完毕后自动换行,如果不想换行请使用end=""编写:

print("Hello world!", end="")

1.1 变量

变量定义格式:变量名 = 变量内容,如massage = 12。(注意,不需要指定数据类型)

1.2 数据类型

  • 字符串

字符串用引号括起来,引号可以是单引号也可以是双引号。字符串之间可以使用+拼接。

方法调用格式:变量名.方法名(参数列表)。字符串常用方法如下:

title():使字符串中各单词首字母大写

upper():使字符串字母全部大写

lower():使字符串字母全部小写

rstrip():删除字符串尾部的空白

lstrip():删除字符串头部的空白

strip():删除字符串首尾的空白

  • 数字

除常见的加、减、乘、除、模运算外,Python还使用两个乘号**表示乘方运算,a ** b即为a的b次方。

使用str()方法避免类型错误:

age = 23
# message = 'Happy' + age + 'rd birthday!'  
# 上面报错,因为Python不知道这里的age是想处理为数值还是字符。
message = 'Happy' + str(age) + 'rd birthday'

第2章 列表

2.1 列表是什么

列表和C语言中的数组比较相似。请见下例:

# 定义列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# 打印列表
print(bicycles)
# 访问列表元素
print(bicycles[0])
print(bicycles[-1].title())

运行结果:

['trek', 'cannondale', 'redline', 'specialized']
trek
Speciaized

列表的索引从0开始,比较特殊的是列表倒数第一个元素可以用-1来访问(如上例所示),倒数第二个用-2来访问,依次类推。

2.2 元素的修改、添加和删除

  • 修改

直接修改即可,如

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles)

运行结果:

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
  • 添加

append(str)方法:将变量str添加到列表的最后。

insert(i, str)方法:将变量str添加到列表的索引i处。

  • 删除

del语句:“del list[i]”可以删除列表list中索引i处的元素。

pop()方法:弹出列表中的最后一个元素,可以用一个变量来接收。

remove(str):将第一次出现的值为str的元素删除。

2.3 组织列表

  • 用sort()方法永久排序

sort()方法可以改变列表中元素的原始排列顺序,按字母序由a到z排列。添加参数reverse=True可改为倒序由z至a排列。

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

cars.sort(reverse=True)
print(cars)

运行结果:

['audi', 'bmw', 'subaru', 'toyota']
['toyota', 'subaru', 'bmw', 'audi']
  • 用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']
  • 用reverse()方法逆序打印列表

这个逆序打印是从后往前打印列表,而不是按照字母顺序倒序打印。它会永久改变列表元素的排列顺序。

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars)

运行结果:

['subaru', 'toyota', 'audi', 'bmw']
  • 用len()方法确定列表的长度

对于上例中的列表cars,len(cars)为4。

2.4 遍历列表

用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('Thank you, everyone. That was a great magic show!')

运行结果:

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!

注意,Python对缩进有很严格的要求。for循环:后指示循环体,循环体必须另起一行且缩进,循环体结束的标志是下一行不缩进(即与for循环首行对齐)。

2.5 创建数值列表

2.5.1 range()函数

Python函数range()可以生成一系列的数字,如:

for value in range(1, 5):
    print(value)

运行结果:

1
2
3
4

注意到上面没有打印数字5,range打印的参数范围是左闭右开的,是常见的差一行为。

可以用range()函数来创建一个列表:

numbers = list(range(1, 5))
print(numbers)

运行结果:

[1, 2, 3, 4]

使用range()时还可以在最后一个参数指定步长。如下例:

numbers = list(range(2, 11, 2))
print(numbers)

运行结果:

[2, 4, 6, 8, 10]

2.5.2 简单的统计计算

min(list):返回列表list的最小元素的值。

max(list):返回列表list的最大元素的值。

sum(list):返回列表list的各元素值的和。

2.5.3 列表解析

将for循环和创建新元素的代码合并成一行,并自动附加新元素:

square = [value**2 for value in range(1, 11)]
print(square)

运行结果:

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

2.6 使用列表的一部分:切片

2.6.1 切片的使用

切片使用示例:

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

运行结果:

['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']

注意依然是左闭右开,与range()一样,除非右边没有写数。

2.6.2 切片的遍历

players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[:3]:
    print(player.title())

运行结果:

Charles
Martina
Michael

2.6.3 用切片实现列表的复制

现有列表a,想把它的内容原封不动复制给列表b,可以这样写:b = a[:]。因为切片创建的是列表的副本,所以b和a是两个不同的列表。倘若这样写:b = a,那么b和a是同一个列表,对这个列表的操作会同时影响a和b的内容。请见下例:

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods 
# 事实上是让Python将新变量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']

2.7 元组

元组就是不可变的列表,列表中的元素的值不可修改。元组用圆括号来定义:dimensions = (200, 50),除值不可变外其余操作与列表用法一致。

值得注意的是,虽然元组中某个元素的值不可修改,但是整个元组可重新定义:

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

第3章 if语句

3.1 条件测试

一个普通的含有if的程序:

cars=['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

运行结果:

Audi
BMW
Subaru
Toyota

if后面跟的条件表达式被称为条件测试。注意逻辑关系“与”和“或”分别用and和or表示,其余的逻辑表达式编写都与C语言相同。

另外,in和not in用于检查某元素是否在特定列表中,请见下例:

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pineapple' not in requested_toppings)

运行结果:

True
False

3.2 if语句的结构

常用的是if-elif-else结构,其中可以不写else分支。

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $"+str(price)+".")

运行结果:

Your admission cost is $5.

第4章 字典

4.1 字典的定义

字典是一系列键值对的集合,可以使用键来访问其对应的值。字典用大括号定义:

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])

运行结果:

green
5

字典也可以用多行定义:

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python', 
    # 这里可以加逗号也可以不加,但是为以后添加键值对方便,最好加一个逗号
}

print("Sarah's favorite language is "+ favorite_languages['sarah'].title()+'.')

运行结果:

Sarah's favorite language is C.

4.2 键值对的添加、修改和删除

  • 添加、修改键值对:直接添加、修改即可。
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
# 添加键值对
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
# 修改键值对
alien_0['color']='yellow'
print(alien_0)

运行结果:

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
{'color': 'yellow', 'points': 5, 'x_position': 0, 'y_position': 25}
  • 删除键值对:del语句
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
# 删除键值对
del alien_0['points']
print(alien_0)

运行结果:

{'color': 'green', 'points': 5}
{'color': 'green'}

4.3 遍历字典

字典中的items()方法代表键值对,keys()方法代表键,values()方法代表值。

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python', 
}
# 遍历键值对
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " +
          language.title() + ".")
# 遍历键
print('--------------------')
for name in favorite_languages.keys():
    print(name.title())
# 遍历值
print('--------------------')
for language in favorite_languages.values():
    print(language.title())

运行结果:

Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
--------------------
Jen
Sarah
Edward
Phil
--------------------
Python
C
Ruby
Python

有时候我们希望按一定顺序遍历键,sorted()方法可按字母顺序遍历所有键。

有时候我们希望遍历值的时候剔除重复的值,set()方法可以剔除重复值。

下面的例子用到了sorted()和set()方法:

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python', 
}

for name in sorted(favorite_languages.keys()):
    print(name.title()+", thank you for taking the poll.")

print('--------------------')
for language in set(favorite_languages.values()):
    print(language.title())

运行结果:

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
--------------------
Python
Ruby
C

4.4 嵌套

4.4.1 字典列表

字典可以作为列表的元素,如:

aliens = [alien_0, alien_1, alien_2]

这里alien_0, alien_1, alien_2都是字典。

我们也可以使用range()来创建包含多个字典的列表:

aliens = []

for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow', 'num': alien_number}
    aliens.append(new_alien)

4.4.2 在字典中存储列表

pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
}

print("You ordered a " + pizza['crust'] + "-crust pizza " +
      "with the following toppings:")
for topping in pizza['toppings']:
    print('\t' + topping)

运行结果:

You ordered a thick-crust pizza with the following toppings:
    mushrooms
    extra cheese

4.4.3 在字典中存储字典

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },

    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    },
    # 一般要求这些字典格式一致
}

for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']

    print('\tFull name: ' + full_name.title())
    print('\tLocation: ' + location.title())

运行结果:

Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton

Username: mcurie
    Full name: Marie Curie
    Location: Paris