《Python编程:从入门到实践》第一部分关键知识点学习笔记

字符串

大小写方法:

title():以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写。

例如,你可能希望程序将值 Ada 、 ADA 和 ada 视为同一个名字,并将它们都显示为 Ada 。

name = "ada lovelace"

print(name.title())

 

upper()与lower():将字符串改为全部大写或全部小写。

name = "Ada Lovelace"

print(name.upper())

print(name.lower())

 

合并(拼接)字符串:

first_name = "ada"

last_name = "lovelace"

full_name = first_name + " " +last_name

message = "Hello, " +full_name.title() + "!"

print(message)

 

删除空白

>>> favorite_language = '  python  '

>>> favorite_language.rstrip()

'  python'

>>> favorite_language.lstrip()

'python  '

>>>  favorite_language.strip()

'python'

 

使用函数str()转换为字符串类型

age = 23

message = "Happy " + str(age) +"rd Birthday!"

print(message)

 

方法 split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。

 

方法 count() 来确定特定的单词或短语在字符串中出现了多少次。

>>>  line = "Row, row, row your boat"

>>>  line.count('row')

2

>>>  line.lower().count('row')

3

 

replace() 将字符串中的特定单词替换为另一个单词。

>>>  message = "I really like dogs."

>>>  message.replace('dog', 'cat')

'I really like cats.'

 

列表

在列表中添加元素

1.      在列表末尾添加元素

motorcycles =['honda', 'yamaha', 'suzuki']

print(motorcycles)

motorcycles.append('ducati')

print(motorcycles)

2.      在列表中插入元素

motorcycles =['honda', 'yamaha', 'suzuki']

motorcycles.insert(0,'ducati')

print(motorcycles)

在列表中删除元素

1.      使用 del 语句删除元素

motorcycles = ['honda', 'yamaha', 'suzuki']

print(motorcycles)

del motorcycles[0]

print(motorcycles)

 

2.      使用方法 pop() 删除元素(方法 pop() 可删除列表末尾的元素和弹出列表中任何位置处的元素)

motorcycles =['honda', 'yamaha', 'suzuki']

print(motorcycles)

popped_motorcycle = motorcycles.pop()

print(motorcycles)

print(popped_motorcycle)

 

motorcycles = ['honda','yamaha', 'suzuki']

first_owned =motorcycles.pop(0)

print('The firstmotorcycle I owned was a ' + first_owned.title() + '.')

3.      根据值删除元素

motorcycles =['honda', 'yamaha', 'suzuki', 'ducati']

print(motorcycles)

too_expensive ='ducati'

motorcycles.remove(too_expensive)

print(motorcycles)

print("\nA " + too_expensive.title() + " istoo expensive for me.")

 

组织列表

1.  使用方法 sort() 对列表进行永久性排序

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

cars.sort(reverse=True)

print(cars)

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

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

print("Hereis the original list:")

print(cars)

print("\nHereis the sorted list:")

print(sorted(cars))

print("\nHereis the original list again:")

print(cars)

3.      倒着打印列表

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

print(cars)

cars.reverse()

print(cars)

4.      确定列表的长度

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

>>>  len(cars)

4

 

操作列表

遍历整个列表

magicians = ['alice', 'david', 'carolina']

for magician in magicians:

print(magician.title()+ ", that was a great trick!")

print("Ican't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was agreat magic show!")

 

创建数值列表

1 使用函数 range()

for value in range(1,5):

print(value)

2 使用 range() 创建数字列表

numbers = list(range(1,6))

print(numbers)

 

even_numbers = list(range(2,11,2))

print(even_numbers)

输出如下:

[2, 4, 6, 8, 10]

 

对数字列表执行简单的统计计算

>>>  digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

>>>  min(digits)

0

>>>  max(digits)

9

>>>  sum(digits)

45

 

列表解析

squares = []

for value in range(1,11):

  squares.append(value**2)

print(squares)

 

squares = [value**2 for value inrange(1,11)]

print(squares)

 

遍历切片

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

print("Here are the first threeplayers on my team:")

for player in players[:3]:

print(player.title())

复制列表

my_foods = ['pizza', 'falafel', 'carrotcake']

friend_foods = my_foods[:]#副本

 

#friend_foods = my_foods  这里将 my_foods 赋给friend_foods ,而不是将 my_foods 的副#本存储到 friend_foods,实际上,它们指向同一个列表,一个改变,另一个也改变

 

print("My favorite foods are:")

print(my_foods)

print("\nMy friend's favorite foodsare:")

print(friend_foods)

 

元组(不可变的列表)

dimensions = (200, 50)

print(dimensions[0])

print(dimensions[1])

 

dimensions[0] = 250会报错:

Traceback (most recent call last):

File "dimensions.py", line 3, in<module>

dimensions[0] = 250

TypeError: 'tuple' object does not supportitem assignment

 

修改元组变量

虽然不能修改元组的元素,但可以给存储元组的变量赋值,即重新定义整个元组。

dimensions = (200, 50)

print("Original dimensions:")

for dimension in dimensions:

print(dimension)

 

dimensions = (400, 100)

print("\nModified dimensions:")

for dimension in dimensions:

print(dimension)

 

相比于列表,元组是更简单的数据结构。如果需要存储的一组值在程序的整个生命周期内都

不变,可使用元组。

 

字典

创建字典

alien_0 = {}

alien_0['color'] = 'green'

alien_0['points'] = 5

修改字典中的值

alien_0 = {'color': 'green'}

print("The alien is " +alien_0['color'] + ".")

alien_0['color'] = 'yellow'

print("The alien is now " +alien_0['color'] + ".")

删除键值对

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

print(alien_0)

del alien_0['points']

print(alien_0)

 

遍历字典

1 遍历所有的键 — — 值对

favorite_languages = {

'jen': 'python',

'sarah': 'c',

'edward': 'ruby',

'phil': 'python',

}

for name, language infavorite_languages.items():

print(name.title()+ "'s favorite language is " +language.title() + ".")

 

2 遍历字典中的所有键

favorite_languages = {

'jen': 'python',

'sarah': 'c',

'edward': 'ruby',

'phil': 'python',

}

for name in favorite_languages.keys():

print(name.title())

 

按顺序遍历字典中的所有键

favorite_languages = {

'jen': 'python',

'sarah': 'c',

'edward': 'ruby',

'phil': 'python',

}

for name insorted(favorite_languages.keys()):

print(name.title()+ ", thank you for taking the poll.")

 

遍历字典中的所有值

favorite_languages = {

'jen': 'python',

'sarah': 'c',

'edward': 'ruby',

'phil': 'python',

}

print("The following languages havebeen mentioned:")

for language inset(favorite_languages.values()):#对包含重复元素的列表调用 set() ,可让#Python找出列表中独一无二的元素

print(language.title())

 

嵌套

字典列表

# 创建一个用于存储外星人的空列表

aliens = []

# 创建30个绿色的外星人

for alien_number in range (0,30):

new_alien = {'color': 'green', 'points': 5,'speed': 'slow'}

aliens.append(new_alien)

for alien in aliens[0:3]:

ifalien['color'] == 'green':

alien['color'] = 'yellow'

alien['speed'] = 'medium'

alien['points'] = 10

# 显示前五个外星人

for alien in aliens[0:5]:

print(alien)

print("...")

 

在字典中存储列表

# 存储所点比萨的信息

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)

 

 

favorite_languages = {

'jen': ['python', 'ruby'],

'sarah': ['c'],

'edward': ['ruby', 'go'],

'phil': ['python', 'haskell'],

}

for name, languages infavorite_languages.items():

print("\n"+ name.title() + "'s favorite languages are:")

   forlanguage in languages:

print("\t" + language.title())

 

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("\tFullname: " + full_name.title())

print("\tLocation:" + location.title())

 

用户输入

height = input("How tall are you, ininches? ")

height = int(height)

if height >= 36:

print("\nYou'retall enough to ride!")

else:

         print("\nYou'llbe able to ride when you're a little older.")

 

responses = {}

# 设置一个标志,指出调查是否继续

polling_active = True

while polling_active:

# 提示输入被调查者的名字和回答

 name = input("\nWhat is your name?")

response =input("Which mountain would you like to climb someday? ")

# 将答卷存储在字典中

     responses[name] = response

# 看看是否还有人要参与调查

     repeat = input("Would you like to let another person respond? (yes/ no)")

if repeat =='no':

polling_active = False

# 调查结束,显示结果

print("\n--- Poll Results ---")

for name, response in responses.items():

print(name +" would like to climb " + response + ".")

 

函数

结合使用位置实参和任意数量实参

def make_pizza(size, *toppings):

"""概述要制作的比萨"""

print("\nMakinga " + str(size) +"-inch pizza with the following toppings:")

for topping intoppings:

print("- " + topping)

 

make_pizza(16, 'pepperoni')

make_pizza(12, 'mushrooms', 'greenpeppers', 'extra cheese')

基于上述函数定义,Python将收到的第一个值存储在形参 size 中,并将其他的所有值都存储在元组 toppings 中。在函数调用中,首先指定表示比萨尺寸的实参,然后根据需要指定任意数量的配料。

 

使用任意数量的关键字实参

def build_profile(first, last,**user_info):

"""创建一个字典,其中包含我们知道的有关用户的一切"""

profile = {}

   profile['first_name']= first

profile['last_name']= last

   forkey, value in user_info.items():

profile[key] = value

return profile

user_profile = build_profile('albert','einstein',location='princeton',field='physics')

print(user_profile)

 

函数 build_profile() 的定义要求提供名和姓,同时允许用户根据需要提供任意数量的名称—值对。形参 **user_info 中的两个星号让Python创建一个名为 user_info 的空字典,并将收到的所有名称— 值对都封装到这个字典中。我们调用 build_profile() ,向它传递名( 'albert' )、姓( 'einstein' )和两个键值对( location='princeton' 和 field='physics' ),并将返回的 profile 存储在变量 user_profile 中,再打印这个变量:

{'first_name': 'albert', 'last_name':'einstein',

'location': 'princeton', 'field': 'physics'}

 

文件和异常

1 从文件中读取数据

with open('pi_digits.txt') as file_object:

contents =file_object.read()

print(contents.rstrip())

 

第一次打印时读取整个文件;

 

2 逐行读取

filename = 'pi_digits.txt'

with open(filename) as file_object:

for line infile_object:

print(line.rstrip())

 

第二次打印时遍历文件对象;

 

3创建一个包含文件各行内容的列表

filename = 'pi_digits.txt'

with open(filename) as file_object:

   lines= file_object.readlines()

for line in lines:

print(line.rstrip())

方法 readlines() 从文件中读取每一行,并将其存储在一个列表中;接下来,该列表被

存储到变量 lines 中;在 with 代码块外,我们依然可以使用这个变量。

 

第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。

 

4. 使用文件的内容

filename = 'pi_30_digits.txt'

with open(filename) as file_object:

lines =file_object.readlines()

pi_string = ''

for line in lines:

pi_string +=line.strip()

print(pi_string)

print(len(pi_string))

 

写入文件

filename = 'programming.txt'

 with open(filename, 'a') as file_object:

file_object.write("Ialso love finding meaning in large datasets.\n")

file_object.write("Ilove creating apps that can run in a browser.\n")

 

分析文本

filename = 'alice.txt'

try:

with open(filename)as f_obj:

contents = f_obj.read()

except FileNotFoundError:

msg ="Sorry, the file " + filename + " does not exist."

print(msg)

else:

# 计算文件大致包含多少个单词

 words = contents.split()

 num_words = len(words)

 print("The file " + filename +" has about " + str(num_words) + " words.")

 

方法 split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。

结果是一个包含字符串中所有单词的列表,虽然有些单词可能包含标点。

 

使用多个文件

def count_words(filename):

 """计算一个文件大致包含多少个单词"""

try:

withopen(filename) as f_obj:

contents = f_obj.read()

except FileNotFoundError:

msg ="Sorry, the file " + filename + " does not exist."

print(msg)

else:

# 计算文件大致包含多少个单词

words =contents.split()

num_words =len(words)

print("Thefile " + filename + " has about " + str(num_words) +"words.")

 

filename = 'alice.txt'

count_words(filename)

 

filenames = ['alice.txt', 'siddhartha.txt','moby_dick.txt', 'little_women.txt']

for filename in filenames:

count_words(filename)

 

存储数据

1 使用 json.dump() 和 json.load()

import json

numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'

with open(filename, 'w') as f_obj:

 json.dump(numbers, f_obj)

 

函数 json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。先导入模块 json ,再创建一个数字列表。我们指定了要将该数字列表存储到其中的文件的名称。通常使用文件扩展名.json来指出文件存储的数据为JSON格式。接下来,我们以写入模式打开这个文件,让 json 能够将数据写入其中。我们使用函数 json.dump()将数字列表存储到文件numbers.json中。

 

打开文件文件numbers.json,看看其内容。数据的存储格式与Python中一样:

[2, 3, 5, 7, 11, 13]

 

使用 json.load() 将这个列表读取到内存中:

import json

filename = 'numbers.json'

with open(filename) as f_obj:

 numbers = json.load(f_obj)

print(numbers)

 

这是一种在程序之间共享数据的简单方式

 

remember_me.py

import json

# 如果以前存储了用户名,就加载它

# 否则,就提示用户输入用户名并存储它

filename = 'username.json'

try:

     with open(filename) as f_obj:

            username = json.load(f_obj)

except FileNotFoundError:

     username = input("What is your name? ")

     with open(filename, 'w') as f_obj:

json.dump(username, f_obj)

print("We'll remember you when you come back, " + username+ "!")

else:

print("Welcomeback, " + username + "!")

 

重构

重构remember_me.py

import json

def greet_user():

 """问候用户,并指出其名字"""

filename = 'username.json'

try:

withopen(filename) as f_obj:

username = json.load(f_obj)

except FileNotFoundError:

username =input("What is your name? ")

withopen(filename, 'w') as f_obj:

json.dump(username, f_obj)

print("We'll remember you when you come back, " + username+ "!")

else:

print("Welcomeback, " + username + "!")

 

greet_user()

 

重构 greet_user() ,让它不执行这么多任务。

import json

def get_stored_username():

 """如果存储了用户名,就获取它"""

filename = 'username.json'

try:

withopen(filename) as f_obj:

username = json.load(f_obj)

except FileNotFoundError:

 return None

else:

return username

 

def greet_user():

"""问候用户,并指出其名字"""

username = get_stored_username()

if username:

print("Welcomeback, " + username + "!")

else:

username =input("What is your name? ")

filename ='username.json'

withopen(filename, 'w') as f_obj:

json.dump(username,f_obj)

print("We'llremember you when you come back, " + username + "!")

greet_user()

 

将 greet_user() 中的另一个代码块提取出来:将没有存储用户名时提示用户输入的

代码放在一个独立的函数中

import json

def get_stored_username():

"""如果存储了用户名,就获取它"""

-- snip –

 

def get_new_username():

"""提示用户输入用户名"""

username = input("What is your name?")

filename = 'username.json'

with open(filename, 'w') as f_obj:

json.dump(username,f_obj)

return username

 

def greet_user():

"""问候用户,并指出其名字"""

username = get_stored_username()

if username:

print("Welcomeback, " + username + "!")

else:

username =get_new_username()

print("We'llremember you when you come back, " + username + "!")

greet_user()

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林下的码路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值