master
/ 01.01 Python 基础.ipynb

01.01 Python 基础.ipynb @masterview markup · raw · history · blame

Notebook

1.1 Python 基础

1.1.1 Python 简介

Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。

  • Python 是一种解释型语言: 开发过程中没有了编译这个环节。

  • Python 是交互式语言: 可以在一个 Python 提示符 >>> 后直接执行代码。

  • Python 是面向对象语言: Python 支持面向对象的风格或代码封装在对象的编程技术。

  • Python 对初学者非常友好:Python 语法简单,可以快速上手,但异常强大,应用也十分广泛,从 web 开发,网络爬虫到机器学习,人工智能,金融量化分析都有广泛的应用。

第一行 Python 代码

In [ ]:
print("hello world!")

1.1.2 数据类型

类型 例子
整数 -100
浮点数 3.1416
字符串 'hello'
列表 [1, 1.2, 'hello']
字典 {'dogs': 5, 'pigs': 3}
长整型 1000000000000L
布尔型 True, False
元组 ('ring', 1000)
集合 {1, 2, 3}

使用type()函数来查看变量类型:

In [ ]:
a = 1
type(a)

Python 中运算是有优先级的,优先级即算术的先后顺序,比如“先乘除后加减”和“先算括号里面的”都是两种优先级的规则,优先级从高到低排列如下:

  • ( ) 括号
  • ** 幂指数运算
  • * / // % 乘,除,整数除法,取余运算
  • + - 加减
In [ ]:
a = 4
b = 3
print("加:", a + b)
print("减:", a - b)
print("乘:", a * b)
print("除:", a / b)
print('幂:', a ** b)
print('取余', a % b)
print('取商:', a // b)

常见的数学函数

绝对值:

In [ ]:
abs(-12.4)

保留小数点位数:

In [ ]:
round(21.6445, 2)

最大最小值:

In [ ]:
print(min(2, 3, 4, 5))
print(max(2, 4, 3))

类型转换

浮点数转整型,只保留整数部分:

In [ ]:
print(int(-3.32))

整型转浮点型:

In [ ]:
print(float(1))

数值型转字符串:

In [ ]:
str(1)

字符串转数字型:

In [ ]:
int('1')

1.1.3 字符串

使用一对单引号' '或者双引号" "生成字符串。

In [ ]:
s = "hello, world"
print(s)
In [ ]:
s = 'hello, world'
print(s)

常见的操作

加法

In [ ]:
a = 'hello'
b = 'world'
a + b

乘法

In [ ]:
c = a * 3
c

分割:
s.split() 将字符串 s 按照空格(包括多个空格,制表符\t,换行符\n等)分割,并返回所有分割得到的字符串。

In [ ]:
line = "1 2 3 4  5"
numbers = line.split()
print(numbers)
type(numbers)

连接
与分割相反,s.join(sequence) 的作用是以 s 为连接符将序列 sequence 中的元素连接起来,并返回连接后得到的新字符串。

In [ ]:
s = ' '
s.join(numbers)

替换
s.replace(part1, part2) 将字符串 s 中指定的部分 part1 替换成想要的部分 part2,并返回新的字符串。

In [ ]:
s = "hello world"
s.replace('world', 'python')

大小写转换

s.upper() 方法返回一个将 s 中的字母全部大写的新字符串。

s.lower() 方法返回一个将 s 中的字母全部小写的新字符串。

In [ ]:
"hello world".upper()
In [ ]:
s = "HELLO WORLD"
print(s.lower())

# 不会改变原来s的值
print(s)

字符串的长度

In [ ]:
len(s)

1.1.4 索引和分片

索引

对于一个有序序列,可以通过索引的方法来访问对应位置的值。字符串便是一个有序序列,Python 使用 下标 来对有序序列进行索引。索引是从 0 开始的,所以索引 0 对应与序列的第 1 个元素。

In [ ]:
s = "hello"
s[0]

除了正向索引,Python 还引入了负索引值的用法,即从后向前开始计数,例如,索引 -1 表示倒数第 1 个元素:

In [ ]:
s[-1]

单个索引大于等于字符串的长度时,会报错:

In [ ]:
s[6]

分片

分片用来从序列中提取出想要的子序列,其用法为:

var[start_index:  stop_index:  step]  

其范围包括 start_index ,但不包括 stop_index ,即 [start_index, stop_index)step 表示取值间隔大小,如果没有默认为1

In [ ]:
s = "hello"
s[::2]

1.1.5 列表

列表是一个有序的序列。

列表用一对 [ ] 生成,中间的元素用 , 隔开,其中的元素不需要是同一类型,同时列表的长度也不固定。

In [ ]:
l = [1, 2.0, 'hello']
print(l)

空列表可以用 [] 或者 list() 生成:

In [ ]:
empty_list = []
empty_list
In [ ]:
empty_list = list()
empty_list

列表的常见操作

长度:用 len 查看列表长度

In [ ]:
l = [1, 2.0, 'hello']
len(l)

加法: 相当于将两个列表按顺序连接

In [ ]:
a = [1, 2, 3]
b = [3.2, 'hello']
a + b

乘法:列表与整数相乘,相当于将列表重复相加

In [ ]:
a * 3

索引和分片

列表和字符串一样可以通过索引和分片来查看它的元素。

索引

In [ ]:
a = [10, 11, 12, 13, 14]
a[0]

反向索引

In [ ]:
a[-1]

分片

In [ ]:
a[2:-1]

添加元素

append:向列表添加单个元素
l.append(ob) 将元素 ob 添加到列表 l 的最后。

In [ ]:
a = [10, 11, 12]
a.append(11)
print(a)

append 每次只添加一个元素,并不会因为这个元素是序列而将其展开:

In [ ]:
a = [10, 11, 12]
a.append(['a', 'b'])
print(a)

extend: 向列表添加序列元素
l.extend(lst) 将序列 lst 的元素依次添加到列表 l 的最后,作用相当于 l += lst

In [ ]:
a = [10, 11, 12]
a.extend(['a', 'b'])
print(a)

insert: 插入元素
l.insert(idx, ob) 在索引 idx 处插入 ob ,之后的元素依次后移。

In [ ]:
a = [10, 11, 12, 13, 11]
# 在索引 3 插入 'a'
a.insert(3, 'a')
print(a)

删除元素

del:根据下标进行删除

In [ ]:
# 根据下标进行删除
a = [1002, 'a', 'b', 'c']
del a[0]
print(a)

pop:弹出元素
l.pop(idx) 会将索引 idx 处的元素删除,并返回这个元素。未指定 idx 时,默认为列表最后一个元素。

In [ ]:
a = [1002, 'a', 'b', 'c']
a.pop()
print(a)

remove:根据元素的值进行删除
l.remove(ob) 会将列表中第一个出现的 ob 删除,如果 ob 不在 l 中会报错。

In [ ]:
a = [1002, 'a', 'b', 'c', 'b']
a.remove("b")
print(a)

测试从属关系

in 来看某个元素是否在某个序列(不仅仅是列表)中;

not in来判断是否不在某个序列中。

In [ ]:
a = [10, 11, 12, 13, 11]
print(10 in a)
print(10 not in a)

index 查找某个元素在列表中的位置:

l.index(ob) 返回列表中元素 ob 第一次出现的索引位置,如果 ob 不在 l 中会报错。

In [ ]:
a = [10, 11, 12, 13, 11]
a.index(11)

count 查找列表中某个元素出现的次数:

In [ ]:
a = [10, 11, 12, 13, 11]
a.count(11)

修改元素

修改元素的时候,要通过下标来确定要修改的是哪个元素,然后才能进行修改

In [ ]:
a = [10, 11, 12, 13, 11]
a[0] = "a"
a

排序

sort方法将 list 按特定顺序重新排列,默认为由小到大,参数 reverse=True 可改为倒序,由大到小

In [ ]:
# 从小到大排序
a = [10, 1, 11, 13, 11, 2]
a.sort()
print(a)
In [ ]:
# 从大到小排序
a = [10, 1, 11, 13, 11, 2]
a.sort(reverse=True)
print(a)

如果不想改变原来列表中的值,可以使用 sorted 函数:

In [ ]:
a = [10, 1, 11, 13, 11, 2]
b = sorted(a)
print("a:",a)
print("b:",b)

列表反向

l.reverse() 会将列表中的元素从后向前排列。

In [ ]:
a = [10, 1, 11, 13, 11, 2]
a.reverse()
print(a)

如果不想改变原来列表中的值,可以使用分片:

In [ ]:
a = [10, 1, 11, 13, 11, 2]
b = a[::-1]
print("a:",a)
print("b:",b)

1.1.6 字典

字典 dictionary ,在一些编程语言中也称为 hashmap ,是一种由键值对组成的数据结构。

顾名思义,我们把键想象成字典中的单词,值想象成词对应的定义,那么——

一个词可以对应一个或者多个定义,但是这些定义只能通过这个词来进行查询。

Python 使用key: value这样的结构来表示字典中的元素结构。

空字典

Python 使用 {} 或者 dict() 来创建一个空的字典:

In [ ]:
a = {}
type(a)
In [ ]:
a = dict()
type(a)

插入键值

In [ ]:
a["one"] = "this is number 1"
a["two"] = "this is number 2"
a["three"] = "this is number 3"
a

注意:
1.字典的键必须是数字、字符串、元组等,不能是列表、字典、集合。
2.字典没有顺序:当我们 print 一个字典时,Python 并不一定按照插入键值的先后顺序进行显示,因为字典中的键本身不一定是有序的。

In [ ]:
# 查看键值
a['one']

更新键值

In [ ]:
a["one"] = "this is number 1, too"
a

get方法

用键可以找到该键对应的值,但是当字典中没有这个键的时候,Python 会报错,这时候可以使用字典的 get 方法来处理这种情况,其用法如下:

d.get(key, default = None)

返回字典中键 key 对应的值,如果没有这个键,返回 default 指定的值(默认是 None )。

In [ ]:
a = {}
a["one"] = "this is number 1"
a["two"] = "this is number 2"

a.get("three", "undefined")

keys 方法,values 方法和items 方法

d.keys() :返回一个由所有键组成的列表;

d.values() :返回一个由所有值组成的列表;

d.items() :返回一个由所有键值对元组组成的列表。

In [ ]:
a = {}
a["one"] = "this is number 1"
a["two"] = "this is number 2"

a.keys()
In [ ]:
a.values()
In [ ]:
a.items()

1.1.7 元组

元组Tuple也是个有序序列,但是元组是不可变的,用()生成。

In [ ]:
# 生成元组
a = ()
type(a)

生成只含有单个元素的元组时,采用下列方式定义:

In [ ]:
# 生成元组
a = (1,)
type(a)

元组是不可变的,修改元组元素时会报错:

In [ ]:
a = (10, 11, 12, 13, 14)
a[0] = 1
a

可以把元组转为列表:

In [ ]:
a = (10, 11, 12, 13, 14)
b = list(a)
print(b)
type(b)

1.1.8 集合

之前看到的列表和字符串都是一种有序序列,而集合 set 是一种无序的序列。

因为集合是无序的,所以当集合中存在两个同样的元素的时候,Python 只会保存其中的一个(唯一性);同时为了确保其中不包含同样的元素,集合中放入的元素只能是不可变的对象(确定性)。

可以用set()函数来显示的生成空集合:

In [ ]:
a = set()
type(a)

也可以使用一个列表来初始化一个集合:

In [ ]:
a = set([1, 2, 3, 1])
a

集合会自动去除重复元素 1

可以看到,集合中的元素是用大括号{}包含起来的,这意味着可以用{}的形式来创建集合:

In [ ]:
a = {1, 2, 3, 1}
a

但是创建空集合的时候只能用set来创建,因为在 Python{}创建的是一个空的字典:

In [ ]:
s = {}
type(s)

1.1.9 判断语句

基本用法

判断,基于一定的条件,决定是否要执行特定的一段代码,例如判断一个数是不是正数:

In [ ]:
x = 0.5
if x > 0:
    print("Hey!")
    print("x is positive")

在这里,如果 x > 0Falsex ≤ 0 ,那么程序将不会执行两条 print 语句。

虽然都是用 if 关键词定义判断,但与 C,Java 等语言不同,Python不使用 {}if 语句控制的区域包含起来。Python 使用的是缩进方法。同时,也不需要用 () 将判断条件括起来。

上面例子中的这两条语句:

print("Hey!")   
print("x is positive")

就叫做一个代码块,同一个代码块使用同样的缩进值,它们组成了这条 if 语句的主体。

不同的缩进值表示不同的代码块,例如:

x > 0 时:

In [ ]:
x = 0.5
if x > 0:
    print("Hey!")
    print("x is positive")
    print("This is still part of the block")
print("This isn't part of the block, and will always print.")

x < 0 时:

In [ ]:
x = -0.5
if x > 0:
    print("Hey!")
    print("x is positive")
    print("This is still part of the block")
print("This isn't part of the block, and will always print.")

在这两个例子中,最后一句并不是 if 语句中的内容,所以不管条件满不满足,它都会被执行。

一个完整的 if 结构通常如下所示(注意:条件后的 : 是必须要的,缩进值需要一样):

if <condition 1>:
    <statement 1>
    <statement 2>
elif <condition 2>: 
    <statements>
else:
    <statements>

当条件 1 被满足时,执行 if 下面的语句,当条件 1 不满足的时候,转到 elif ,看它的条件 2 满不满足,满足执行 elif 下面的语句,不满足则执行 else 下面的语句。

对于上面的例子进行扩展:

In [ ]:
x = 0
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

elif 的个数没有限制,可以是1个或者多个,也可以没有。

else 最多只有1个,也可以没有。

可以使用 andornot 等关键词结合多个判断条件:

In [ ]:
x = 10
y = -5
x > 0 and y < 0
In [ ]:
not x > 0
In [ ]:
x < 0 or y < 0

这里使用这个简单的例子,假如想判断一个年份是不是闰年,按照闰年的定义,这里只需要判断这个年份是不是能被 4 整除,但是不能被 100 整除,或者正好被 400 整除:

In [ ]:
year = 1900
if year % 400 == 0:
    print("This is a leap year!")
# 两个条件都满足才执行
elif year % 4 == 0 and year % 100 != 0:
    print("This is a leap year!")
else:
    print("This is not a leap year.")

判断条件为 False 情况总结:

Python 不仅仅可以使用布尔型变量作为条件,它可以直接在 if 中使用任何表达式作为条件:

大部分表达式的值都会被当作 True,但以下表达式值会被当作 False

  • False
  • None
  • 0
  • 空字符串,空列表,空字典,空集合
In [ ]:
mylist = [3, 1, 4, 1, 5, 9]
if mylist:
    print("The first element is:", mylist[0])
else:
    print("There is no first element.")

修改为空列表:

In [ ]:
mylist = []
if mylist:
    print("The first element is:", mylist[0])
else:
    print("There is no first element.")

1.1.10 循环

循环的作用在于将一段代码重复执行多次。

while 循环

while <condition>:
    <statesments>

Python 会循环执行<statesments>,直到<condition>不满足为止。

例如,计算数字0100的和:

In [ ]:
i = 0

# 求和结果
total = 0

# 循环条件
while i < 100:
    # 求和累加
    total += i
    # 变量递增
    i += 1
    
# 打印结果
print(total)

之前提到,空容器会被当成 False ,因此可以用 while 循环来读取容器中的所有元素:

In [ ]:
plays = ['Hamlet', 'Macbeth', 'King Lear']
while plays:
    play = plays.pop()
    print('Perform', play)

循环每次从 plays 中弹出一个元素,一直到 plays 为空为止。

for 循环

for <variable> in <sequence>:
    <indented block of code>

for 循环会遍历完<sequence>中所有元素为止

上一个例子可以改写成如下形式:

In [ ]:
plays = ['Hamlet', 'Macbeth', 'King Lear']
for play in plays:
    print('Perform', play)

使用 for 循环时,注意尽量不要改变 plays 的值,否则可能会产生意想不到的结果。

之前的求和也可以通过 for 循环来实现:

In [ ]:
total = 0
for i in range(100):
    total += i
print(total)

continue 语句

遇到 continue 的时候,程序会返回到循环的最开始重新执行。

例如在循环中忽略一些特定的值:

In [ ]:
values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
    if i % 2 != 0:
        # 忽略奇数
        continue
    print(i/2)

break 语句

遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足:

In [ ]:
command_list = ['start',
                'process',
                'process',
                'process',
                'stop',
                'start',
                'process',
                'stop']
while command_list:
    command = command_list.pop(0)
    if command == 'stop':
        break
    print(command)

在遇到第一个 'stop' 之后,程序跳出循环。

else 语句

if 一样, whilefor 循环后面也可以跟着 else 语句。

  • 当循环正常结束时,循环条件不满足, else 被执行;
  • 当循环被 break 结束时,循环条件仍然满足, else 不执行。

不执行 else 语句:

In [ ]:
values = [7, 6, 4, 7, 19, 2, 1]
for x in values:
    if x <= 10:
        print('Found:', x)
        break
else:
    print('All values greater than 10')

执行 else 语句:

In [ ]:
values = [11, 12, 13, 100]
for x in values:
    if x <= 10:
        print('Found:', x)
        break
else:
    print('All values greater than 10')