廖雪峰学习 Python
pycharm 的 使用 mac 版
pycharm 使用 mac2
Python 基础篇 字典列表元组等
自用标签
爬取视频 lux+”链接“
基础
- 牛顿迭代法
注释
"""
多
行
注
释
"""
或
'''
多
行
注
释
'''
1.检测数据类型 type(数据)
list 列表 [1,2,3]
tuple 元组 (1,2,3)
set 集合 {1,2,3}
dict 字典 {‘name’:‘Tom’,‘age’:18}
2.格式化输出
%s 字符串
%d 有符号的十进制数
%f 浮点数
weight = 65.5
print('体重是%f.2岁' %weight) # 保留几位在 f 后加.数字
student_id = 3
print('学号是%03d' %student_id) #三位数,不足三位前面补 0 输出 003,超出的原样输出
age = 18
print('my age is %d,and 明年%d岁.' %(age,age+1))
f 直接格式化输出(py3.6)
print(f'my name is {name},明年{age + 1}岁了')
转义字符
/n 换行 /t 制表符(一个 tab 键(4 个空格)的距离)
结束符(print 默认结束是换行/n)
print(' ' , end = "...")
输入 并赋值
x = input("提示信息") #数据类型为 str
数据类型转换
eval() --计算在字符串中的有效 python 表达式,并返回一个对象(把字符串里转换成原本的类型)
运算符
-
算术运算符 //整除 **指数
-
赋值运算符
-
复合赋值运算符 c += a <<->> c = c+a 先计算复合赋值运算符右边的运算,再复合赋值。
-
比较运算符
-
逻辑运算符 and(有0则0,否则结果为最后一个非0数) or(所有为0才0,否则为第一个非0数) not
求模运算符%,将两个数相除并返回余数。
条件语句
if True:
print(' ')
elif (18<=age<=60):
print(' ')
else:
print(' ')
导入模块 import 模块名
- 三目运算符 条件成立执行的表达式 if 条件 else 条件不成立执行的表达式
循环 while for
break 终止循环
continue 退出当前一次循环(本次循环continue 后的不执行) 继续下一次循环 (一定要在 continue 前就修改计数器)
打印一行五个* while 循环 然后 print(‘*’,end=‘’) 用 end 取消换行
str1 = 'nmsl'
for i in str1:
print('i')
while else 循环 当while 正常完成循环后才执行else后的 break 不执行 continue 执行
字符串
三引号字符串可以多行
切片
str1 = '073028902'
`print(str1[2:5:1])`#取不到结束位置数
`print(str1[-4:-1:-1])`#不能选取出数据 选取数据方向与步长方向冲突
常用操作方法
- -find() 检测某个子串是否包含在这个字符串中,如果在,返回索引(第一个出现的子串的第一个字母的索引);否则返回-1
- -index() 检测某个子串是否包含在这个字符串中,如果在,返回索引;否则报错
- -count() 计算出现的次数
- -rfind() 右侧开始查找的第一个子串的正向索引
- str.find(子串,开始位置下标,结束位置下标)#空格也算
- -replace() 替换 不改变原字符串(字符串是不可变数据类型)
字符串.replace(旧子串,新子串,替换次数)#替换次数超出子串个数表示替换所有子串,默认替换所有 - -split() 按指定字符分割字符串
字符串序列.split(分割字符,num) #返回 num+1 个数据,分割字符丢失 - -join() 合并列表里的字符串数据为一个大字符串
- -capitalize() 只有首字母大写,串内大写会被改成小写
- -title() 每个单词首字母都大写
- -lower() 所有都变小写
- -upper() 所有都变大写
- -lstrip() 删除左侧空白字符
- -rstrip() 删除右侧空白字符
- -strip() 删除两侧空白字符
- -ljust() 字符串左对齐,不足用填充字符(默认空格)
字符串序列.ljust(长度,填充字符) - -center() 中间对齐
判断
- startwith() 检查字符串是否以指定子串开头,是返回 true 否返回 false
字符串序列.startswich(子串,开始位置下标,结束位置下标) - endwith() …
- isalpha() 如果至少有一个字符且所有字符都是字母返回 true
- isdigit() 如果只包含数字返回 true
- isalnum() 如果至少有一个字符且所有字符都是数字或字母返回 true
- isspace() 如果只包含空白返回 true
列表 [数据 1,数据 2,数据 3…]
查找
name_list = ['Tom','Lily','Rose']
print(name_list)
print(name_list[0])
- -index() 返回指定数据所在位置下标
- -count() 统计指定数据在当前列表中出现次数
- -len() 访问列表长度
列表序列.index(数据,开始位置下标,结束位置下标)
索引-1 为最后一个元素
print(name_list.count('Tom'))
print(len(name_list))
- -in 判断指定数据在某个列表序列,如果在返回 True
-not in 判断不在
print('Lily' in name_list)
- append() 列表结尾增加数据 如果是序列,整个序列[]放进列表结尾
- extend() 列表结尾增加数据
如果是序列,将序列数据逐一加到结尾 - insert() 指定位置增加数据
列表序列.append(数据)
列表序列.insert(位置下标,数据)
name_list.extend('xiaoming')
print(name_list)
['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']
name_list.extend(['xiaoming'])
print(name_list)
['Tom', 'Lily', 'Rose', 'xiaoming']
- del 目标 删除列表、指定下标数据
- pop() 删除指定下标的数据,默认最后一个数据。返回的都是被删除的数据
- remove() 删除指定的一个数据(第一个匹配项)
- clear() 清空列表
修改列表
- reverse() 逆置
- sort() 升序(默认)或降序(永久性排序)
列表序列.sort(reverse=False) #升序
列表序列.sort(reverse=True) #降序 - sorted 临时排序
- copy() 复制列表
- title() 首字母大写
- lower() 转换为小写
range(1,6,2) #打印 1-5 每隔 2
list(range(1,6)) #转为列表
列表的循环遍历
- while 遍历
name_list = ['Tom','Lily','Rose']
i = 0
while i < len(name_list):
print(name_list[i])
i = i + 1
- for 遍历
for i in name_list:
print(i)
列表嵌套
name_list = [['小红','小明','小绿'],['Tom','Lily','Rose'],['张三','李四','王五']]
print(name_list[2][1])#拿到李四
八名老师随机分配给三个办公室
import random
teachers = ['a','b','c','d','e','f','g','h']
offices = [[],[],[]]
for name in teachers:
num = random.randint(0,2)
offices[num].append(name)
print(offices)
元组
一个元组可以存储多个数据,元组内的数据不能修改
t = (10,20,30)
print(type(t))#tuple
t1 = (10,)#如果定义元组只有一个数据,这个数据后最好也添加逗号,否则数据类型为唯一这个数据的数据类型
- index() 查找
- count() 统计某数据在当前元组出现的次数
- len() 统计元组数据个数
#如果元组里有列表,可修改列表里的数据
t2 = ('aa','bb',['cc','dd'])
t2[2][0] = 'Tom'
print(t2) #('aa', 'bb', ['Tom', 'dd'])
字典
创建
dict1 = {'name':'Tom','age':20,'gender':'男'}
dict2 = {} #空字典
dict3 = dict()
操作
- 字典序列[key] = 值 (key 存在就修改 key 对应值,不存在就增加键值对)
增加
dict1['name'] = 'Rose'
dict1['id'] = 110
删除
del(dict1) #删完字典找不到
del dict1['gender']
dict1.clear() #变成空字典
修改 与增加差不多
查找
print(dict1['name']) #Tom 不存在则报错
字典序列.get(key,默认值) #如果当前查找的 key 不存在则返回第二个参数(默认值),如果省略第二个参数,则返回 None
print(dict1.get('name')) #Tom
print(dict1.get('id',110)) #110
print(dict1.get('id')) #None
print(dict1.keys()) #查找字典中所有的 key,返回可迭代对象(可用 for 循环遍历)
print(dict1.values()) #查找字典中所有的值,返回可迭代对象
print(dict1.items()) #查找字典中所有的键值对,返回可迭代对象。
里面数据为元组,元组数据一是 key 元组数据二是 key 对应值
遍历键值对
items每个键值对
keys 每个键
values 每个值
dict1 = {'name':'Tom','age':20,'gender':'男'}
for key,value in dict1.items():
print(f'{key}={value}')
集合
创建集合用{},set(),创建空集合只能用 set() 因为{}用来创建空字典
无序性(输出顺序无序) 唯一性(不显示重复数据)
增加
-
add()
-
update() 增加的数据是序列[]
删除
- remove() 删除集合中指定数据,不存在则报错
- discard() 删除集合中指定数据,不存在不报错
- pop() 随机删除某个数据,并返回这个数据
查找
in/not in
s1 = {10,20,30}
print(10 in s1) #True
公共操作
运算符 + 合并 字符串、列表、元组
* 复制 字符串、列表、元组
str1 = 'a'
print(str1*5) #aaaa
- range(start,end,step) 生成 start 到 end 的数字(不包含 end),步长为 step 供 for循环用。
- enumerate(可遍历对象,start=0) 将可遍历数据对象组合为一个索引序列,返回元组,列出数据和数据下标。
for i in range(1,10,1):
print(i) #1 2 3 4 5 6 7 8 9
for i in range(10) #默认起点 0 步长 1
print(i) #0 1 2 3 4 5 6 7 8 9
list1 = ['a','b','c','d','e']
for i in enumerate(list1):
print(i) #(0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e')
for index,char in enumerate(list1,start=1):
print(f'下标是{index},对应字符是{char}')
- 容器类型转换
tuple()
list()
set()
推导式 (列表 字典 集合)
list1=[]
for i in range(10)
list1.append(i)
print(list1)
列表推导式
list1 = [i for i in range(10)]
print(list1)
带 if 列表推导式
list1 = [i for i in range(10) if i%2 ==0]
print(list1)
多个 for循环实现列表推导式
list1 = [(i,j) for i in range(1,3) for j in range(3)]
print(list1) #[(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)] 在列表中追加元组
字典推导式
快速合并列表为字典
dict1 = {i:i**2 for i in range(1,5)}
print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16}
list1 = ['name','age','gender']
list2 = ['Tom','18','man']
dict1 = {list1[i]:list2[i] for i in range(len(list1))}
print(dict1) # {'name': 'Tom', 'age': '18', 'gender': 'man'}
提取字典目标数据
counts = {'MBP':268,'HP':125,'DELL':201,'Lenovo':199,'acer':99}
count1 = {key:value for key,value in counts.items() if value>=200}
print(count1) # {'MBP': 268, 'DELL': 201}
集合推导式
list1 = [1,1,2]
set1 = {i**2 for i in list1}
print(set1) # {1, 4}
其他基础学习代码
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
print ("Mary had a little lamb." )
print( "Its fleece was white as %s." % 'snow')
print ("And everywhere that Mary went." )
print ("." * 10 )#what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
#watch that comma at the end.
print (end1 + end2 + end3 + end4 + end5 + end6,end = " " )#和下一行连接起来!
print (end7 + end8 + end9 + end10 + end11 + end12 )
# 5-30 能被 5整除的数
s = 1
for i in range(5,31,5):
s = s*i
print('积为',s)
formatter = "%r %r %r %r"
print (formatter %(1,2,3,4))
print (formatter %("one","two","three","four"))
print (formatter %(True,False,False,True))
print (formatter %(formatter,formatter,formatter,formatter))
print (formatter %(
" I had this thing.",
" That you could type up right.",
" But it didn't sing.",
" So I said goodnight."
))
# Here's some new strange stuff ,remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print ("Here are the days :",days)
print("Here are the month:",months)
print ("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want,or 5,or 6.
""")
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "\nI'm\\a\\cat."
fat_cat = """
I'll do a list:
\t*Cat food
\t*Fishes
\t*Catnip\n\t*Grass
"""
print(tabby_cat + persian_cat + backslash_cat + fat_cat)
import pandas as pd
df = pd.DataFrame([
['green','M',20,'class1'],
['red','L',21,'class2'],
['blue','XL',30,'class3']])
df.columns = ['color','size','weight','class label']
pd.get_dummies(df['color'])
def make_great(magician_list ):
for i in range(len(magician_list )):
magician_list[i] = 'the Great ' + magician_list [i]
def show_magician(magician_list):
[print(magician) for magician in magician_list]
magician_list = ['cs','mjk','lyh']
make_great(magician_list)
show_magician(magician_list)
import math
pi = math.pi
birthday = input("enter your birthday, in the form mmddyy: ")
if birthday in pi:
print("appear")
else:
print("not")
print ("How old are you?"),
age = input()
print("How tall are you?"),
height = input()
print("How much do you weight?"),
weight = input()
print("So,you're %r years old, %r tall and %r heavy."%(age,height,weight))
from sys import argv
script,first,second,third = argv
print"The script is called:",script
print"Your first variable is :",first
print"Your second variable is :",second
print"Your third variable is :",third
prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program."
message = ""
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
unconfirmed_users = ['alice','brain','candace']
confirmed_users = []
while unconfirmed_users :
current_user = unconfirmed_users.pop()
print("verifying users: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
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 + '.')
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止。
#打印每个设计后,都将其移到 complete_models 列表中。
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根据设计制作 3D 打印模型的过程。
print ("Printing model: " + current_design)
completed_models.append(current_design)
#显示打印好的所有模型
print("\nThe following models have been printed: ")
for completed_model in completed_models:
print(completed_model)
def make_pizza(size,*toppings):
"""概述要制作的披萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings: ")
for topping in toppings:
print("- " + topping)
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert','einstein',
location = 'princeton',
field = 'physics')
print(user_profile)
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
""" 初始化属性 name 和 age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + "is now sitting.")
def roll_over(self):
""" 模拟小狗被命令时打滚"""
print(self.name.title() + "rolled over !")
my_dog = Dog('罗宇鸿', 20)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + "years old.")
my_dog.sit()
my_dog.roll_over()
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
self.tank_reading = 1
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车历程的消息"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""将里程表读数设置为指定的值
并禁止将里程表读数往回调"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer !")
def increment_odometer(self, miles):
"""将里程表读数增加指定的量"""
self.odometer_reading += miles
def fill_gas_tank(self):
print("This car has " + str(self.tank_reading) + " tank on it.")
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self,battery_size=70):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def get_range(self):
"""打印一条消息,指出电瓶的续航里程"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += "miles on a full charge."
print(message)
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "kWh battery." )
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
""" 初始化父类的属性"""
super().__init__(make,model,year)
self.battery = Battery()
# def describe_battery(self):
# """打印一条描述电瓶容量的消息"""
# print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self):
"""电动车没有油箱"""
print("This car doesn't need a gas tank ! ")
my_new_car = Car('audi','a4',2016)
print (my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_odometer(23)#调整里程表
my_new_car.read_odometer()
my_new_car.update_odometer(20)# 不能往回调
my_used_car = Car('subaru','outback','2013')
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
my_used_car.fill_gas_tank()
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.fill_gas_tank()
my_tesla.battery.get_range()
def solve(str_list):
word_table = sorted(list(set((' '.join(str_list)).split())))
str2index = {}
index_list = []
for i in range(len(word_table)):
str2index[word_table[i]] = i + 1
for nums in str_list: #每一句话就新增一个[]
index_list.append([])
for num in nums.split():
index_list[-1].append(str2index[num]) #负一是指在最后一个列表里放索引
#如果-1改成 0 结果就为 ['four', 'one', 'three', 'two', 'zero'] [[2, 4, 3, 4, 2, 1, 5], []]
return word_table, index_list,
if __name__ == "__main__":
str_list = "one two three", "two one four zero"
word_table, index_list = solve(str_list)
print(word_table)
print(index_list)
#word_table = {'four','one','three','two','zero'}
#str_index_list = {[2 4 3],[4 2 1 5]}.