目前最新《2018机器学习40讲》

Python基础自学之路
变量和简单数据类型
2.2变量
添加变量将导致Python解释器需要更多工作
在程序中可以随时修改变量的值,而Python始终记录变量的最新值
2.2.1变量的命名和使用
变量名只能包含字母,数字,下划线。
可以以字母下划线打头,但不能用数字打头
变量名中间不能有空格,可以使用下划线分割单词,如greeting_message
不能将Python关键字和函数名作为变量名
变量名应该简短同时具有描述性
建议少用小写字母l和字母oO,因为任意被看成是数字
2.2.2使用变量时避免命名错误
很多编程都很简单,但却有不少优秀的成员因为变量名字这样的微小错误而而花费大量时间
2.3字符串
在Python中,用引号引起来的都时字符串,可以是单引号,也可以是双引号,如下也是合理的
message = "'xxx','sss"
print(message)
1
2
2.3.1使用方法修改字符串的大小写
# 将字符串首字母大写
title = "title"
title = title.title()
print(title)

# 将字符串全部大写
title1 = title.upper()
print(title1)

# 将字符串全部小写
title2 = title1.lower()
print(title2)
1
2
3
4
5
6
7
8
9
10
11
12
存储数据时,lower()方法很有用,很多时候无法依靠用户提供正确的大小写,需要将字符串全部化为小写,再存储,需要显示时,将将其转为需要的大小写方式
2.3.2合并字符串
# 合并字符串
firstName = "yuan"
lastName = "tuo"
fullName = firstName + lastName
print(fullName)

# 上述操作的整合
message = "Hello " + fullName.title() + "!"
print(message)
1
2
3
4
5
6
7
8
9
2.3.4删除空白
Python能够发现字符串中的空白,例如"Python" 和 "Python " 是两个不同的字符串
# rstrip() 可以去除尾部空白
message = " xxxx "
print(message.rstrip())

# lstrip() 可以去除首部空白
print(message.lstrip())

# strip() 可以去除两端空白
print(message.strip())
1
2
3
4
5
6
7
8
9
2.4整数
终端会话中,Python会直接返回运算结果
Python使用两个乘号表示乘方,不能使用多个表示多次方
print(2 ** 9)

# 下面这种写法是错误的
# print(2 *** 9)
1
2
3
4
2.4.2浮点数
Python将带小数点的数字都称之为浮点数

有时候位数是不确定的

# 会输出0.30000000000000004
print(0.1 + 0.2)
1
2
2.4.3使用str()避免类型转化错误
age = 23
print("Hello My Love,Your age is " + str(age))
1
2
2.6Python之禅
尽可能的避繁就简
代码需要优雅而漂亮
选择简单的的解决方案
编写有益的注释
解决方案大家应该尽量一致
不要企图编写完美无缺的代码,应该编写行之有效的代码,在做进一步改进
列表简介
3.1列表是什么
列表是一系列按照特定元素组成
可以将任何东西加入列表中,他们之间可以没有任何关系
Python使用[ ]表示列表,使用逗号分隔元素
bicycles = ['trek', 'redline', 'specialized']
print(bicycles)
1
2
# 通过索引访问元素
print(bicycles[0])

# 取出列表第一个元素并且首字母大写
print(bicycles[0].title())

# 通过-号访问倒数的元素
print(bicycles[-1])
1
2
3
4
5
6
7
8
3.2修改,添加,删除元素
你所创建的列表通常是动态的,将随着程序的运行而变化
3.2.1修改列表元素
# 通过索引直接修改
bicycles = ['trek', 'redline', 'specialized']
bicycles[0] = "test"
print(bicycles)
1
2
3
4
3.2.2在列表中添加元素
# 在列表末尾添加元素
bicycles = ['trek', 'redline', 'specialized']
bicycles.append("test1")
print(bicycles)
1
2
3
4
# 通过insert()将元素插入指定位置
bicycles = ['trek', 'redline', 'specialized']
bicycles.insert(1, "test")
print(bicycles)
1
2
3
4
3.2.3从列表中删除元素
# 通过del删除指定位置的元素
bicycles = ['trek', 'redline', 'specialized']
del bicycles[1]
print(bicycles)
1
2
3
4
使用pop()可以删除列表末尾的元素,并且能够让你继续使用它
bicycles = ['trek', 'redline', 'specialized']
test = bicycles.pop()
print(test)
print(bicycles)
1
2
3
4
使用pop()弹除列表中指定位置的元素,在括号中指定索引即可
bicycles = ['trek', 'redline', 'specialized']
test = bicycles.pop(1)
print(test)
print(bicycles)
1
2
3
4
通过remove()删除指定值的元素,但是只会删除第一个
3.3组织列表
你所创建的列表中,排序常常是无法预测的
有时候你想保留列表元素最初的元素顺序,有时候有需要重新排序,Python都对其增加了支持
3.3.1使用sort()对列表进行永久性排序
# 使用sort()方法按照首字母大小写进行反向排序
# 需要注意的是在Python中,True And False 是首字母大写
cars = ["bmw", "audi", "subaru"]
cars.sort(reverse=True)
print(cars)
1
2
3
4
5
3.3.2使用sorted对列表进行临时性排序
cars = ["bmw", "audi", "subaru"]
print(sorted(car s))
print(cars)
1
2
3
3.3.3倒着打印列表
# 使用reverse()方法对列表进行永久排序,但是并非是按照字母顺序进行排序,而是按照先后顺序进行倒着排序
cars = ["bmw", "audi", "subaru"]
cars.reverse()
print(cars)
1
2
3
4
操作列表
4.1遍历整个列表
cars = ["audi", "bmw", "benz"]
for car in cars:
    print(car)
1
2
3
上段代码分析:Python首先会获取到cars里的第一个值auid,然后存进变量car中,将其打印,然后获取到bmw,依次循环
对于列表中的元素,都将执行循环特定的步骤,如果包含一百万个元素,Python执行的速度也是很快的
cars = ["audi", "bmw", "benz"]
for car in cars:
    print(car)
    print(car.title()+" is very good")
print("test")    
1
2
3
4
5
注意上面代码的缩进,缩进是控制该方法是否循环体执行的原因,因为Python是根据代码与前一行的缩进来判断关系
4.3创建数值列表
4.3.1使用函数range()
# 这个语句看似会打印1到5,但实际上只会打印1到4
for val in range(1, 5):
    print(val)
1
2
3
4.3.2使用range()创建数字列表
# 使用list()将数字转化为列表
list = list(range(1, 5))
print(list.insert(0, 2))
print(list)
1
2
3
4
# 2到15之间的偶数
evenNumbers = list(range(2, 15, 2))
print(evenNumbers)
1
2
3
# 创建1到10的数平方的列表
squares = []
for val in range(1, 11):
    squares.append(val**2)
print(squares)
1
2
3
4
5
4.3.3对数字列表进行简单的统计运算
print(max(squares))
print(min(squares))
print(sum(squares))
1
2
3
4.3.4列表解析
# 使用列表解析
squares = [val**2 for val in range(1, 15)]
print(squares)
1
2
3
4.4.1切片
要创建切片,可以指定要使用的第一个元素和最后一个元素的所以,可以使用负号(-)表示倒数
players = ["yuan", "han", "su", "wang"]
print(players[0:2])
# 全部打印
print(players[:])
# 打印倒数三个
print(players[-3:])
1
2
3
4
5
6
# 遍历切片
for val in players[-2:]:
    print(val.title())
1
2
3
4.4.3复制列表
# 复制列表 可以发现使用切片复制是两个不相干的实体,是一种完全复制
newPlayers = players[:]
print(newPlayers)
newPlayers.append("xxx")
print(players)
print(newPlayers)

# 可以发现通过变量名赋值,并非完全复制,两个变量名字指向的是同一个对象
print("-----")
newPlayers = players
newPlayers.append("xxx")
print(players)
print(newPlayers)
1
2
3
4
5
6
7
8
9
10
11
12
13
4.5元组
列表非常适合于存储程序运行期间可能变化的数据集,列表是可以修改的
有时候,如果你想创建一组数据不可以被修改可以使用元组
4.5.1定义元组
元组看起来像列表,但是是使用圆括号而不是方括号
4.5.2遍历元组中的值
和遍历列表的操作是一样的
for val in dimensions:
    print(val)
1
2
4.5.3修改元组变量
虽然不能修改元组的值,但是可以个元组变量重新赋值
dimensions = (100, 80)
dimensions = (200, 100)
for val in dimensions:
    print(val)
1
2
3
4
条件测试
5.2.7检查特定值是否包含在列表中
cars = ['bmw', 'benz', 'audi']
if "bmw" in cars:
    print("在里面")
if "bmwa" not in cars:
    print("不在里面")
else:
    print("在里面")
1
2
3
4
5
6
7
5.4.2确定列表不是空的
cars = []
if (cars):
    print("car")
else:
    print("空的")
1
2
3
4
5
第五章总结
2019年3月30日23:00:35

第五章比较简答,感觉没有必要浪费太多时间在这个上面,简单的写点就好了。语法规则上感觉和C,Java差不多的。应该没什么问题。

字典
6.1一个简单的字典
alien0 = {"color" : "blue", "size": "12"}
print(alien0["color"])
print(alien0["size"])
1
2
3
6.2.2添加键值对
字典是一个动态结构,可以随时添加键值对
alien0 = {"color" : "blue", "size": "12"}
alien0["name"] = "yuan"
print(alien0)
1
2
3
6.2.4修改字典中的值
alien0 = {"color" : "blue", "size": "12"}
alien0["color"] = "red"
print(alien0)
1
2
3
6.2.5删除字典中的值
alien0 = {"color" : "blue", "size": "12"}
del alien0["color"]
print(alien0)
1
2
3
6.3遍历字典
一个Python字典可能包含几个键值对,也可能包含数百万个键值对,Python支持字典遍历
6.3.1遍历所有的键值对
alien0 = {"color" : "blue", "size": "12", "exe" : "10"}
for key, val in alien0.items():
    print(key)
    print(val)
1
2
3
4
6.4嵌套
有时候,需要将一系列字典存储在列表中,这称之为嵌套
6.4.1在列表中嵌套字典
alien0 = {"color" : "blue", "size": "12", "exe" : "10"}
alien1 = {"color" : "red", "size": "12", "exe" : "10"}
alien2 = {"color" : "yellow", "size": "12", "exe" : "10"}

aliens = [alien0, alien1, alien2]
for alien in aliens:
    print(alien)
1
2
3
4
5
6
7
# 使用range()生产多个外星人
alien = []
alien0 = {"color": "blue", "size": "12", "exe": "10"}
for val in range(30):
    alien.append(alien0)
for val in alien:
    print(val)
1
2
3
4
5
6
7
# 使用切片修改后5个外星人信息
for val in alien[-5:]:
    if val['color'] == 'blue':
        val['size'] = '15'
for val in alien:
    print(val)
1
2
3
4
5
6
6.4.2在字典中存储列表
favoriteLanguages = {
    "yuan" : ["ruby", "java", "python"],
    "tuo": ["ruby", "php", "python"],
}
 
for key, val in favoriteLanguages.items():
    print(key + "最喜欢的语言是:")
    for v in val:
        print(v)
1
2
3
4
5
6
7
8
9
6.4.3在字典中存储字典
users = {
    "yuan": {
        "firstName": "yuan",
        "lastName": "tuo",
        "location": "sc"
    },

    "tuo": {
        "firstName": "tuo",
        "lastName": "yuan",
        "location": "cs"
    }
}
for key, val in users.items():
    fullName = val["firstName"] + val["lastName"]
    location = val["location"]
    print(fullName + " " + location)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
用户输入和while循环
7.1函数Input()
message = input("Tell me your name!")
print("Hello:" + message)
1
2
7.3.1在列表之间移动元素
# 未验证的用户信息
unconfirmedUsers = ["alice", "mike", "yuan"]
# 已经验证的用户信息
confirmedUsers = []

# 一直验证,直到该列表为空时
while unconfirmedUsers:
    # 获得当前验证的用户信息
    currentUser = unconfirmedUsers.pop()
    # 打印正在验证信息
    print("Verifying user is " + currentUser.title())
    confirmedUsers.append(currentUser)

print("\nThe following users has been confirmed:")

# 显示已经验证的人的信息
for val in confirmedUsers:
    print(val)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
7.3.2删除包含特定值得所有列表元素
pets = ["cat", "cat", "dog", "pig"]
while "cat" in pets:
    pets.remove("cat")
print(pets)
1
2
3
4
函数
8.1定义一个简单的函数
def greet_user():
    print("hello")
greet_user()
1
2
3
8.1.1向函数传递信息
def greet_user1(username):
    print("Hello: " + username.title())
greet_user1("yuan")
1
2
3
8.2.2关键字实参
是传递给函数的键值对
def hello(first_name, last_name):
    print("Hello:" + first_name.title() + last_name.title())
hello(first_name="yuan", last_name="tuo")
1
2
3
8.2.3传递实参时可以知指定默认值
def hello(first_name, last_name = "xxx"):
    print("Hello:" + first_name.title() + last_name.title())
hello(first_name="yuan")
1
2
3
8.3返回简单直
def get_full_name(first_name, last_name):
    full_name = first_name.title() + " " + last_name.title()
    return full_name


my_name = get_full_name("yuan", "tuo")
print(my_name)
1
2
3
4
5
6
7
8.3.2让实参变成可选的
Python将空字符串解读为true
def get_full_name(first_name, last_name, middle_name=''):
    if middle_name:
        full_name = "test"
    else:
        full_name = first_name.title() + " " + last_name.title()
    return full_name


my_name = get_full_name("yuan", "tuo", "xx")
1
2
3
4
5
6
7
8
9
8.3.3返回字典
函数可以返回任何类型的值
def get_name(first, last):
    return {"first": first, "last": last.title()}


person = get_name("yuan", "tuo")
print(person)
1
2
3
4
5
6
结合使用函数和while循环
while True:
    first_name = input("Please input your first name!")
    last_name = input("Please input your last name!")
    full_name = get_full_name(first_name, last_name)
    print(full_name)
1
2
3
4
5
8.4传递列表
def greet_user(names):
    for name in names:
        print("Hello " + name.title())


namess = ["yuan", "tuo", "han"]
greet_user(namess)
1
2
3
4
5
6
7
8.4.1在函数中修改列表
在函数中对列表的任何操作都是永久性的,这能够高效处理大量数据
def print_models(unprinted_designs, completed_designs):
    """
    模拟打印每个设计
    :param unprinted_designs:
    :param completed_designs:
    :return:
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model:" + current_design)
        completed_designs.append(current_design)


my_unprinted_designs = ["case1", "case2", "case3"]
my_completed_designs = []
print_models(my_unprinted_designs, my_completed_designs)

print(my_completed_designs)
print(my_unprinted_designs)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
8.4.2禁止函数修改列表
def print_models(unprinted_designs, completed_designs):
    """
    模拟打印每个设计
    :param unprinted_designs:
    :param completed_designs:
    :return:
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model:" + current_design)
        completed_designs.append(current_design)


my_unprinted_designs = ["case1", "case2", "case3"]
my_completed_designs = []
# 使用[:] 就可以避免函数修改列表了  
print_models(my_unprinted_designs[:], my_completed_designs)

print(my_completed_designs)
print(my_unprinted_designs)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
8.5传递任意数量的实参
有时候你预先不知道需要接收多少个实参,所以需要传递任意数量的实参
def make_pizza(*toppings):
    for topping in toppings:
        print(topping)


make_pizza('mushrooms', 'green peppers', 'extra cheese', "test")
1
2
3
4
5
6
8.5.1结合使用位置实参和任意数量实参
Python会先匹配实参和关键字实参,将在剩余的实参收集到最后一个形参中
8.5.2使用任意数量的关键字实参
有时候需要接收任意数量的实参,但是预先不知道传递给函数式什么样的信息
此时可以将函数编写成能够接受任意数量的键值对,调用语句提供了多少就使用多少
def build_profile(first, last, **user_info):
    profile = {}
    profile["first_name"] = first.title()
    profile["last_name"] = last.title()

    for key, val in user_info.items():
        profile[key] = val
    return profile


my_profile = build_profile("yuan", "tuo", location="石窝", sex="男")
print(my_profile)
1
2
3
4
5
6
7
8
9
10
11
12
8.6将函数存储在模块中
函数的优点是,使用它可以将代码块与主程序分离

--------------------- 
作者:一年花开花谢 
来源:CSDN 
原文:https://blog.csdn.net/qq_40118570/article/details/89061691 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/laohan159/article/details/89194403