2018.9.17——2018.9.26
-
Modules
1.math包
import math
root = math.sqrt(99)计算99的开根号
flr = math.floor(89.9)得到89,向下取整?
math.ceil() 向上取整?
2.导入包时可以将其化简:
import math as m
从包中导入所有function:
from math import *
3.在math包中,pi = π
4.csv文件的读取(最后转化为列表包列表格式)
import csv
f = open("nfl.csv", 'r')
csvreader = csv.reader(f)
nfl = list(csvreader)
-
class不是很懂!
1.class定义类,类内部的代码属于对类型的描述,相当于刻画模板
类内部定义的函数一般称为方法
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
class Dataset:
——def init(self):
———self.type = "csv"
dataset = Dataset()
print(dataset.type)
2.
![](https://img.haomeiwen.com/i13050346/c3f40b801381feef.png)
3.
![](https://img.haomeiwen.com/i13050346/dfdd1e004bb4bb2a.png)
4.enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
enumerate(sequence, [start=0])
![](https://img.haomeiwen.com/i13050346/716262cda33ed704.png)
5.set()函数只返回列表中的unique element,即 F F F M M M 空格,空格,空格 会返回F,M以及空格
6.问题:ini和str是什么鬼?
7.感受一下ini和str:
![](https://img.haomeiwen.com/i13050346/0387ce4ae17a729e.png)
运行结果:
汤姆的年龄是:40
蓝猫的年龄是:10
-
Error Handling
1.试验错误,如果try后面的代码那么久打印出....
try:
——float("hello")
except Exception:
——print("Error converting to float.")
2.更进一步,打印出错误的类型以及错误的具体情况
try:
——int('')
except Exception as exc:
——print(type(exc))
——print(str(exc))
3.except冒号后面可是是pass,意思是如果try当前走不通就跳过当前走下一个?
-
List Comprehensions
- enumerate()功能可以使for循环的body中含有两个变量,index与value
for i, ship in enumerate(ships):
其中i是循环的ships这个list中每个value对应的位置
2.apple_prices = [100, 101, 102, 105]
apple_prices_doubled = [price*2 for price in apple_prices]
apple_prices_lowered = [price-100 for price in apple_prices]
3.此处的b的值是TRUE/FALSE,即判断等号后面的是否正确
a = None
b = a is not None and a > 10
更具体一点:
values = [None, 10, 20, 30, None, 50]
checks = []
checks = [x is not None and x > 30 for x in values]
其中列表checks中的element都是FALSE/TRUE
4.字典.items的食用方法,for循环中可以设置key和value,分别对应字典中的A:B
fruits = {
—"apple": 2,
—"orange": 5,
—"melon": 10
}
for fruit, rating in fruits.items():
—print(fruit)
5.数每个人名出现的次数
male_name_counts = {}
if name in male_name_counts:
—male_name_counts[name] = male_name_counts[name] + 1
else:
—male_name_counts[name] = 1
-
Challenge: Modules, Classes, Error Handling, And List Comprehensions
1.有关于class还是不是很懂,包括ini与str
class Suspension():
—def init(self,row):
——self.name = row[0]
——self.team = row[1]
——self.games = row[2]
——self.year = row[5]
third_suspension = Suspension(nfl_suspensions[2])
print(third_suspension)
-
Variable Scopes
1.sum()的用法,括号内是一个list
sum([6, 11])
2.global设置全局变量
def......
—global a
-
Regular Expressions
1.通用符号
b.t = bXt
^a以a开头
a$以a结尾
strings = ["bat", "robotics", "megabyte"]
regex = "b.t"
"[bcr]at" = "bat" "cat" "rat"
![](https://img.haomeiwen.com/i13050346/8bc56dfcacc8ccc5.png)
2.打印出list前十行
for post in posts[:10]:
—print(post)
3.读取的csv转化为List
import csv
f = open("askreddit_2015.csv", 'r')
csvreader = csv.reader(f)
posts_with_header = list(csvreader)
4.re包
import re
re.search(regex, string)可以检查string是否与regex匹配
of_reddit_count = 0
for row in posts:
—if re.search("of Reddit", row[0]) is not None:
——of_reddit_count += 1
re.sub替换
pattern: The regex to match.反斜杠加数字(\N),则对应着匹配的组(matched group).比如\6,表示匹配前面pattern中的第6个group
repl: The string that should replace the substring matches被替换的字符串/函数
如果repl是字符串的话,其中的任何反斜杠转义字符,都会被处理的。
\n:会被处理为对应的换行符
\r:会被处理为回车符;
其他不能识别的转移字符,则只是被识别为普通的字符:
比如\j,会被处理为j这个字母本身
反斜杠加g以及中括号内一个名字,即:\g<name>,对应着命了名的组,named group
string: The string containing the pattern we want to search
5.re,search时间year 1000-2999
re.search("[1-2][0-9][0-9][0-9]", string)
对于其中重复的三个[0-9]可以用[0-9]{3}来表示
6.re.findall返回一个包含查找内容的list
如 re.findall("[a-z]", "abc123")将会返回["a", "b", "c"]
years = re.findall("[1-2][0-9]{3}", years_string)就会查找year_string中包含1000-2999的年
-
dates in python
1.import time导入time包
current_time = time.time()查看当前时间
tm_year: The year of the timestamp
tm_mon: The month of the timestamp (1-12)
tm_mday: The day in the month of the timestamp (1-31)
tm_hour: The hour of the timestamp (0-23)
tm_min: The minute of the timestamp (0-59)
将现在的时间转化为struct_time
time.gmtime(current_time)
此处先将现在的时间转化为struct格式然后提取小时
current_struct_time = time.gmtime(current_time)
current_hour = current_struct_time.tm_hour
2.import datetime导入datetime包
datetime.datetime.utcnow()查看当前时间
datetime.datetime.year/month/day......查看当前的年、月、日。。。
手动设置一个时间,没设置的时分秒都是000
datetime.datetime(year=2233, month=3, day=22)
timedelta可以用来表示一段时间
datetime.timedelta(weeks = 3, days = 2)
用上面的一个时间点减去timedelta的一段时间就可以往前/往后推多少天,得到多少天之前/后的一个时间点
3.strftime
mystery_date.strftime("%I:%M%p on %A %B %d, %Y")
打印出来的结果12:00AM on Thursday December 31, 2015
4.将Unix timestamps先转化为float然后再用datetime.datetime.fromtimestamp转化为需要的时间格式
float_stamp = float(row[2])
datetime.datetime.fromtimestamp(float_stamp)
5.用for循环查找月份为三月的数据数
march_count = 0
for row in posts:
—if row[2].month == 3:
——march_count += 1
-
Guided Project: Exploring Gun Deaths In The US
1.有关于字典、列表的数数
years = []
year_counts = {}
for row in data:
—years.append(row[1])
for year in years:
—if year not in year_counts:
——year_counts[year] = 0
—else:
——year_counts[year] += 1
print(year_counts)最后得出的是该字典中每个year有多少条
2.简化方法
原始:
dates = []
for row in data:
—year = int(row[1])
—month = int(row[2])
—date =datetime.datetime(year,month,day= 1)
—dates.append(date)
简化后:
dates = [datetime.datetime(year=int(row[1]), month=int(row[2]), day=1) for row in data]
3.接之前的,如何去除重复的日期?
date_counts = {}
for date in dates:
—if date not in date_counts:
——date_counts[date] = 0
—else:
——date_counts[date] += 1
这样输出就是一个字典,key就是每个不同的date,value就是每个date出现的次数
4.总结1-3:
问题:分类汇总,例如每条信息都包含有各自的日期
首先建立一个空白的列表,用for循环逐条读取日期将其填入进列表
其次建立一个新的字典,key即不重复的日期,value即出现的次数
套路是用for循环之前那个包含全部日期的列表,如果element不在列表之中,那么字典[列表] = 0,反之即为
字典[列表] += 1在原有的基础上+1,这样全部循环一遍就可以获得一个字典,key就是各不相同的日期,value就是在原始数据中这些日期的计数。
网友评论