斯坦福CS224N课程_Python简明复习教程_cs224n-python-review-code-updated (第一部分)

6 篇文章 0 订阅

斯坦福CS224N课程前面有个Python的复习材料,是放在正式课程开始前供大家复习熟悉Python用的,我之前学习这个课程的时候略过了。但回头翻资料时发现这个材料对Python初学或不怎么常用的同学来说,还是个很不错的参考,可以速查一些Python的常用用法,以及一些小技巧,觉得值得翻译出来分享一下。

这个是个开放的资料,原文地址在:http://web.stanford.edu/class/cs224n/readings/cs224n-python-review-code-updated.pdf

0.0.1 Agenda

1. 安装

2. 基础

3. Iterables 可迭代对象

4. Numpy (用于数学和矩阵运算)

5. Matplotlib (用于绘图)

6. Q&A

[1]:​​​​​​​

# 注:本教程基于 Python 3.8
# 但也适用于所有 Python 3.X 版本
# 请注意本教程并不十分详尽
# 我们力图包含课程作业中所有能用到的内容
# 但建议你去查询更多的资料
#
# 其他教程:
# NUMPY:
# https://cs231n.github.io/python-numpy-tutorial/#numpy
# https://numpy.org/doc/stable/user/quickstart.html
# MATPLOTLIB:
# https://matplotlib.org/gallery/index.html
# BASICS:
# https://www.w3schools.com/python/
# 多查查这些资料:官方文档、Google、Stack-overflow

0.0.2 1. 安装

安装Anaconda用于运行环境管理

常用命令:

conda env list <– 列表所有的环境

conda create -n newenv python=3.8 <– 创建新环境 
conda enc create -f env.yml <– 从配置文件创建环境 
conda activate envname <– 激活环境 
conda deactivate <– 退出环境

pip install packagename <– 为当前环境安装软件包 
jupyter notebook <– 在当前环境里打开 jupyter

使用 conda/pip 安装软件包 【视频演示】

推荐的 IDE开发环境:

Spyder (Anaconda内置) 
Pycharm (最流行的选择,兼容Anaconda) 

(我平时使用Microsoft Visual Studio Code,用习惯了觉得也不错,尤其是它自带的Terminal也可以配置环境)

[2]:

# 常用 anaconda 命令
#conda env list
#conda create -n name python=3.8
#conda env create -f env.yml
#conda activate python2.7
#conda deactivate
#install packages
#pip install <package>

 0.0.3 2. 基础

https://www.w3schools.com/python/

[3]:

# input and output
# 输入和输出
name = input()
print("hello, " + name)

224N

hello, 224N

[4]:

# print multiple variables separated by a space
# 以空格分隔,打印多个变量
print("hello", name, 1, 3.0, True) 

 hello 224N 1 3.0 True

[5]:

# line comment
# 行注释
"""
block
comments
块注释
"""

 '\nblock \ncomments\n'

[6]:

# variables don't need explicit declaration 
# 变量不需要显式声明
var = "hello" # string 字符串

var = 10.0 # float 浮点型

var = 10 # int  整型
var = True # boolean 布尔型

var = [1,2,3] # list列表指针
var = None # 空指针

[7]:

# type conversions
# 类型转换
var = 10
print(int(var))
print(str(var))
print(float(var))

10

10

10.0

[8]:

# basic math operations
# 基本数学运算
var = 10

print("var + 4 =", 10 + 4)

print("var - 4 =", 10 - 4)

print("var * 4 =", 10 * 4)

print("var ^ 4=", 10 ** 4)

print("int(var) / 4 =", 10//4)	# // 整型除法

print("float(var) / 4 =", 10/4) # / 浮点数除法 
# All compound assignment operators available
# 所有复合赋值运算符都可用
# including += -= *= **= /= //=

# pre/post in/decrementers not available (++ --) 
# 前置/后置/递减器不可用(++ --)

var + 4 = 14

var - 4 = 6

var * 4 = 40

var ^ 4= 10000

int(var) / 4 = 2

float(var) / 4 = 2.5

[9]:

# basic boolean operations include "and", "or", "not"
# 基本布尔运算 "and", "or", "not"
print("not True is", not True) 
print("True and False is", True and False) 
print("True or False is", True or False) 

not True is False

True and False is False

True or False is True

[10]:

# String operations

# 字符串运算(操作)
# '' and "" are equivalent

# '' 和 "" 是等价的

s = "String"


#引号嵌套
#s = 'Mary said "Hello" to John' 
#s = "Mary said \"Hello\" to John" 

# basic

# get length of string and any iterable type
# 取字符串长度,和任意可迭代类型的长度
print(len(s))
# get char by index

# 根据索引取字符
print(s[0]) 
print(s[1:3]) # [1,3)

print("This is a " + s + "!") 

# handy tools 
# 方便的用法
print(s.lower()) 
print(s*4) 
print("ring" in s) 
print(s.index("ring")) 

# slice by delimiter
# 按分隔符切片
print("I am a sentence".split(" "))

# concatenate a list of string using a delimiter 
# 使用分隔符合并字符串列表
print("...".join(['a','b','c'])) 

# formatting variables
# 格式化变量
print("Formatting a string like %.2f"%(0.12345)) 
print(f"Or like {s}!") 
6
S
tr
This is a String!
string
StringStringStringString
True
2
['I', 'am', 'a', 'sentence']
a...b...c
Formatting a string like 0.12
Or like String!

[ ]:

# control flows
# NOTE: No parentheses or curly braces
#       Indentation is used to identify code blocks
#       So never ever mix spaces with tabs 
# 流控制
# 注意:没有括号或大括号
#      缩进用于标识代码块
#      所以永远不要把空格和制表符混在一起

for i in range(0,5):
    for j in range(i, 5):
        print("inner loop")
    print("outer loop")

[11]:

# if-else
var = 10
if var > 10:
    print(">")
elif var == 10:
    print("=")
else:
    print("<")

=

[12]:

# use "if" to check null pointer or empty arrays
# 使用“if”检查空指针或空数组

var = None
if var:
    print(var)
var = []
if var:
    print(var)
var = "object"
if var:
    print(var)

object

[13]:

# while-loop
var = 5
while var > 0:
    print(var)
    var -=1





1

[14]:

# for-loop
for i in range(3): # prints 0 1 2
    print(i)
"""
equivalent to
等价于
for (int i = 0; i < 3; i++)
"""

print("-------")
# range (start-inclusive, stop-exclusive, step)
# range (包括开始, 包括停止, 步长)
for i in range(2, -3, -2):
    print(i) 
"""
equivalent to
等价于
for (int i = 2; i > -3; i-=2)
"""

0
1

------- 
2

-2

[15]:

# define function
# 定义函数
def func(a, b): 
    return a + b
func(1,3)

4

[16]:

# use default parameters and pass values by parameter name
# 使用默认参数并按参数名称传递值
def rangeCheck(a, min_val = 0, max_val=10):
    return min_val < a < max_val # syntactic sugar 语法糖
rangeCheck(5, max_val=4)

False

[17]:

# define class
# 定义类
class Foo:
    # optional constructor
    # 可选构造函数
    def __init__(self, x):
        # first parameter "self" for instance reference, like "this" in JAVA
        # 实例引用的第一个参数“self”,如同JAVA中的“this”
        self.x = x

    # instance method
    # instance reference is required for all function parameters
    # 所有函数参数都需要实例引用
    def printX(self):
        print(self.x)

    # class methods, most likely you will never need this
    # 类方法,很可能您永远不会需要它
    @classmethod
    def printHello(self):
        print("hello")

obj = Foo(6)
obj.printX()

6

[18]:

# class inheritance - inherits variables and methods 
# You might need this when you learn more PyTorch 
# 类继承-继承变量和方法
# 当您学了更多PyTorch时,您可能需要这个
class Bar(Foo):
    pass

obj = Bar(3)
obj.printX()

3

0.0.4 3. Iterables 可迭代类型

[19]:

# linear, size not fixed, not hashable
# 线性,大小不固定,非哈希
alist = list() 

# linear, fixed size, hashable
# 线性、固定大小、可哈希
atuple = tuple() 

# hash table, not hashable, stores (key,value) pairs 
# 哈希表,不可哈希,存储(键、值)对
adict = dict() 

# hash table, like dict but only stores keys
# 哈希表,与dict类似,但只存储键
aset = set() 

# shallow copy
# 浅拷贝
acopy = alist.copy() 

# gets size of any iterable type
# 获取任何可迭代类型的大小
print(len(alist)) 

0

[20]:

# examplar tuple usage
# creating a dictionary to store ngram counts 
# 示例元组用法
# 创建字典以存储ngram计数
d = dict()
d[("a","cat")] = 10
d[["a","cat"]] = 11
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-20-47597361a541> in <module>
3 d = dict()
4 d[("a","cat")] = 10 ----> 5 d[["a","cat"]] = 11
TypeError: unhashable type: 'list'

[21]:

"""
List: not hashable (i.e. can't use as dictionary key)
      dynamic size
      allows duplicates and inconsistent element types
      dynamic array implementation

List: 不可哈希(例如:不能用作字典键)
      动态大小
      允许重复和不一致的元素类型
      动态数组实现
"""
# list creation
# 列表创建
# empty list, equivalent to list() 
# 空列表,相当于list()
alist = [] 
# initialized list
# 初始化列表
alist = [1,2,3,4,5] 
print(alist[0])
alist[0] = 5
print(alist)

print("-"*10)
# list indexing
# 列表索引
# get first element (at index 0) 取第一个元素(在索引0处)
print(alist[0])
# get last element (at index len-1) 取最后一个元素(在索引len-1处)
print(alist[-2]) 
# get elements starting from index 3 (inclusive) 取从索引3开始的元素(包括)
print(alist[3:]) 
# get elements stopping at index 3 (exclusive) 取在索引3处停止的元素(不包括)
print(alist[:3]) 
# get elements within index range [2,4) 获取索引范围[2,4)内的元素
print(alist[2:4]) 
# prints nothing because index is out of range 不打印任何内容,因为索引超出范围
print(alist[6:]) 
# returns a reversed list 返回一个反向列表
print(alist[::-1]) 

print("-"*10)
# list modification
# 列表修改
# insert at end 末端插入
alist.append("new item") 
# insert at index 0 在索引0处插入
alist.insert(0, "new item") 
# concatenate lists 串联列表
alist.extend([2,3,4]) 
# above line is equivalent to alist += [2,3,4] 
#上一行相当于alist+=[2,3,4]

# search by content 按内容搜索
alist.index("new item") 
# remove by content 按内容删除
alist.remove("new item") 
# remove by index 按索引删除
alist.pop(0) 
print(alist)



print("-"*10)
if "new item" in alist:
    print("found") 
else:
    print("not found")

print("-"*10)
# list traversal 
# 列表遍历
for ele in alist:
    print(ele)


print("-"*10)
# or traverse with index
# 或使用索引进行遍历
for i, ele in enumerate(alist):
    print(i, ele)

1
[5, 2, 3, 4, 5]
----------
5
4
[4, 5]
[5, 2, 3]
[3, 4]
[]
[5, 4, 3, 2, 5]
----------
[2, 3, 4, 5, 'new item', 2, 3, 4]
----------
found
----------
2
3
4
5
new item
2
3

---------- 
0 2
1 3
2 4
3 5
4 new item 
5 2
6 3
7 4
 

[22]:

"""
Tuple: hashable (i.e. can use as dictionary key)
       fixed size (no insertion or deletion)
Tuple: 可哈希(例如可以用作字典键)
       固定大小(无插入或删除)
"""
# it does not make sense to create empty tuples
# 创建空元组是没有意义的
atuple = (1,2,3,4,5)
# or you can cast other iterables to tuple
# 或者您可以将其他ITerable转换为tuple
atuple = tuple([1,2,3])

# indexing and traversal are same as list
# 索引和遍历与列表方法是一样的

[23]:

"""
Named tuples for readibility
命名元组以便可读
"""
from collections import namedtuple 
Point = namedtuple('Point', 'x y') 
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5) 
print(pt1.x, pt1.y)

1.0 5.0

[24]:

"""
Dict: not hashable
      dynamic size
      no duplicates allowed
      hash table implementation which is fast for searching
Dict: 不可哈希
      动态大小
      不允许重复
      快速搜索的哈希表实现
"""
# dict creation
# 字典创建
# empty dict, equivalent to dict() 
# 空字典,相当于dict()
adict = {} 
adict = {'a':1, 'b':2, 'c':3}
print(adict)

# get all keys in dictionary
# 取字典里所有的key
print(adict.keys())

# get value paired with key
# 取key配对的值
print(adict['a'])
key = 'e'

# NOTE: accessing keys not in the dictionary leads to exception
# 注意:访问字典中没有的键会导致异常
if key in adict: 
    print(adict[key])

# add or modify dictionary entries 
# 添加或修改字典条目
adict['e'] = 10 #插入新key 
adict['e'] = 5 # 修改已有的key

print("-"*10)
# traverse keys only 
# 仅遍历key
for key in adict:
    print(key, adict[key])

print("-"*10)
# or traverse key-value pairs together 
# 或者一起遍历键值对
for key, value in adict.items():
    print(key, value)

print("-"*10)
# NOTE: Checking if a key exists
# 注意:检查key是否存在
key = 'e'
if key in adict: # NO .keys() here please! 这里不用.keys()
    print(adict[key]) 
else:
    print("Not found!")

{'a': 1, 'b': 2, 'c': 3}
dict_keys(['a', 'b', 'c'])
1
10
---------- 
a 1
b 2
c 3
e 5 
---------- 
a 1
b 2
c 3
e 5 
---------- 
5

[25]:

"""
Special dictionaries
特殊字典
"""
# set is a dictionary without values 
# set是没有值的字典
aset = set()
aset.add('a')

# deduplication short-cut using set
# 使用set快速数据去重
alist = [1,2,3,3,3,4,3]
alist = list(set(alist))
print(alist)

# default_dictionary returns a value computed from a default function 
# for non-existent entries
# 对于不存在的条目,用default_dictionary返回从默认函数计算的值
from collections import defaultdict
adict = defaultdict(lambda: 'unknown')
adict['cat'] = 'feline'
print(adict['cat'])
print(adict['dog'])

[1, 2, 3, 4]
feline
unknown

[26]:

# counter is a dictionary with default value of 0 
# and provides handy iterable counting tools 
# counter是默认值为0的字典
# 并提供方便易用的可迭代型对象的计数工具
from collections import Counter

# initialize and modify empty counter
# 初始化并修改空counter
counter1 = Counter()
counter1['t'] = 10
counter1['t'] += 1
counter1['e'] += 1
print(counter1)

print("-"*10)

# initialize counter from iterable
# 从可迭代对象初始化counter
counter2 = Counter("letters to be counted")
print(counter2)
print("-"*10)

# computations using counters
# 使用counter计算
print("1", counter1 + counter2)
print("2,", counter1 - counter2)
print("3", counter1 or counter2) # 或用于交集和并集

Counter({'t': 11, 'e': 1})
----------
Counter({'e': 4, 't': 4, ' ': 3, 'o': 2, 'l': 1, 'r': 1, 's': 1, 'b': 1, 'c': 1,
'u': 1, 'n': 1, 'd': 1})
----------
1 Counter({'t': 15, 'e': 5, ' ': 3, 'o': 2, 'l': 1, 'r': 1, 's': 1, 'b': 1, 'c':
1, 'u': 1, 'n': 1, 'd': 1})
2, Counter({'t': 7})
3 Counter({'t': 11, 'e': 1})

[27]:

# sorting
# 排序
a = [4,6,1,7,0,5,1,8,9]
a = sorted(a)
print(a)
a = sorted(a, reverse=True) 
print(a)

[0, 1, 1, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 1, 1, 0]
 

[28]:

# sorting
# 排序
a = [("cat",1), ("dog", 3), ("bird", 2)] 
a = sorted(a)
print(a)
a = sorted(a, key=lambda x:x[1]) 
print(a)

[('bird', 2), ('cat', 1), ('dog', 3)]
[('cat', 1), ('bird', 2), ('dog', 3)]
 

[29]:

# useful in dictionary sorting
# 在字典排序中很有用
adict = {'cat':3, 'bird':1} 
print(sorted(adict.items(), key=lambda x:x[1]))
[('bird', 1), ('cat', 3)]

[30]:

# Syntax sugar: one-line control flow + list operation
# 语法糖:单行控制流+列表操作
sent = ["i am good", "a beautiful day", "HELLO FRIEND"] 
"""
for i in range(len(sent)):
    sent[i] = sent[i].lower().split(" ")
"""
sent1 = [s.lower().split(" ") for s in sent] 
print(sent1)

sent2 = [s.lower().split(" ") for s in sent if len(s) > 10] 
print(sent2)

# Use this for deep copy!
# 用下面这个做深度复制!
# copy = [obj.copy() for obj in original]

[['i', 'am', 'good'], ['a', 'beautiful', 'day'], ['hello', 'friend']]
[['a', 'beautiful', 'day'], ['hello', 'friend']]

[31]:

# Syntax sugar: * operator for repeating iterable elements
#语法糖:*操作符用于重复可迭代元素
print("-"*10)
print([1]*10)

# Note: This only repeating by value
#       So you cannot apply the trick on reference types
#注意:这仅按值重复,因此,不能对引用类型应用此技巧

# To create a double list 
# 创建双重列表
# DONT
# 不要这么做
doublelist = [[]]*10 
doublelist[0].append(1) 
print(doublelist)
# DO
# 要这么做
doublelist = [[] for _ in range(10)] 
doublelist[0].append(1) 
print(doublelist)

----------
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
[[1], [], [], [], [], [], [], [], [], []]

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值