文章目录
- 字符串
- 函数
- Str(),int()强制类型转换
- 列表
- 排序
- 遍历
- 删除
- 数值列表
- 字典
- 访问:
- 遍历
- 添加
- 删除
- 嵌套
- 字典组成的列表
- 列表组成的字典
- 字典组成的字典
- 条件
- if条件
- while
- Break,continue
- 用户输入
- 函数
- 定义
- 传参
- 关键字实参
- 返回值
- 在函数中修改列表
- 禁止函数修改列表
- 传递任意数量的实参
- 数据处理
- plot 直线图
- plot散点图
- 色彩渐变
字符串
函数
print(name.title()) #title 函数让每个单词的开头大写
print(name.upper()) # 全部大写
print(name.lower()) # 全部小写
加号(+ )来合并字符串。
message=message.lstrip()# 删除字符串左边空白
message=message.rstrip()# 删除字符串右边空白
’ 应该放在“ ”之间
Str(),int()强制类型转换
age=23
message = "Happy " + str(age) + "rd Birthday!"
列表
cycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)#Python将打印列表的内部表示,包括方括号
motorcycles.append('ducati') #在列表末尾添加元素
motorcycles.insert(0, 'ducati') #指定新元素的索引和值。
del motorcycles[0]#如果知道要删除的元素在列表中的位置,可使用del 语句。
popped_motorcycle = motorcycles.pop()
print(motorcycles)#pop() 可删除列表末尾的元素,并让你能够接着使用它。
first_owned = motorcycles.pop(0)
#你可以使用pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可
motorcycles.remove('ducati')#如果你只知道要删除的元素的值,可使用方法remove() 。方法remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值
排序
sort() 对列表进行永久排序
sorted() 对列表进行临时排序
reverse(),len()
每当需要访问最后一个列表元素时,都可使用索引-1,仅当列表为空时,这种访问最后一个元素的方式才会导致错误
遍历
❶ magicians = ['alice', 'david', 'carolina']
❷ for magician in magicians:
❸ print(magician)
for magician in magicians:
❶ print(magician.title() + ", that was a great trick!")
对于位于for 语句后面且属于循环组成部分的代码行,一定要缩进。
删除
while 'cat' in pets:
pets.remove('cat')
数值列表
for value in range(1,5):
print(value)
#1 2 3 4
range(2,11,2)#从2开始数,然后不断地加2,直到达到或超过终值(11)
numbers = list(range(1,6))#可使用函数list() 将range() 的结果直接转换为列表。
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
squares = [value**2 for value in range(1,11)]
#首先指定一个描述性的列表名,如squares ;然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )
字典
字典 是一系列键—值对:alien_0 = {‘color’: ‘green’, ‘points’: 5}
访问:
alien_0 = {'color': 'green'}
print(alien_0['color'])
遍历
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
遍历键:for name in favorite_languages.keys(): print(name.title())
按键顺序打印:for name in sorted(favorite_languages.keys()): print(name.title() + “, thank you for taking the poll.”)
即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。
遍历值:
for language in favorite_languages.values():
print(language.title())
为剔除重复项,可使用集合(set)。集合 类似于列表,但每个元素都必须是独一无二的:
for language in set(favorite_languages.values()):
print(language.title())
添加
alien_0 = {}#创建空的
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
删除
del alien_0['points']
嵌套
字典组成的列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_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)
字典组成的字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris', },
}
for username, user_info in users.items():#user_info 又是一个字典
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())
条件
if条件
age = 12
if age<4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")#允许省略else 代码块
and; or ;in ;not in
确定列表不是空的
requested_toppings = []
if requested_toppings:#我们首先创建了一个空列表,其中不包含任何配料(见❶)。在❷处我们进行了简单检查,而不是直接执行for 循环。在if 语句中将列表名用在条件表达式中 时,Python将在列表至少包含一个元素时返回True ,
while
while current_number <= 5:
print(current_number) current_number += 1
Break,continue
while True:
city = input(prompt)
if city == 'quit': break
else:
print("I'd love to go to " + city.title() + "!")
用户输入
message = input("Tell me something, and I will repeat it back to you: ")
input() 接受一个参数:即要向用户显示的提示 或说明,让用户知道该如何做。
函数
定义
def greet_user():
"""显示简单的问候语""" #文档字符串 (docstring)的注释,描述了函数是做什么的。文档字符串用三引号括 起,Python使用它们来生成有关程序中函数的文档。这不会在控制台被打印
print("Hello!")
传参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
关键字实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆(不会得到名为Hamster的harry这样的结果)。关键字实参让 你无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。
默认值
def describe_pet(pet_name, animal_type=‘dog’):
返回值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name ❸ return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
在函数中修改列表
将列表传递给函数后,函数就可对其进行修改。def print_models(unprinted_designs, completed_models):
禁止函数修改列表
函数调用:function_name(list_name[:])
切片表示法[:] 创建列表的副本
传递任意数量的实参
数据处理
plot 直线图
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=5)
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14) # 'both'影响x 轴和y 轴上的刻度
plt.show()
plot散点图
import matplotlib.pyplot as plt
# 散点图
x_values = [1, 2, 3, 4, 5]
# 比C++简单好多呢!和MATLAB相似
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, s=50) #在x,y画大小为50的点
plt.show()
色彩渐变
import matplotlib.pyplot as plt
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
# c可以指定颜色,(r,g,b)范围0-1,越接近1,颜色越浅
# plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolor='none', s=40)
# 参数c 设置成了一个 y 值列表,并使用参数cmap 告诉pyplot 使用哪个颜色映射。
# 这些代码将 y 值较小的点显示为浅蓝色,并将 y 值较大的点显示为深蓝色
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40)
# 设置图表标题并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])
# 设置刻度标记的大小,major设置主刻度线
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()