2、基本类型
python中使用 pep8
python中定义变量名非驼峰命名法,而是“全为小写字母,单词之间用下划线隔开“,例如first_name
python严格区分大小写,例如False才能作为bool值
#
表示注释
\\
\'
\"
\n
表示转义字符
fruit = "Apple"
print(fruit[1:-1]) # ppl
格式化字符串
first = "Mosh"
second = "Hamedani"
full = f"{first} {second}" # Mosh Hamedani
full = f"{len(first)} {second}" # 4 Hamedani
x = input("x: ")
y = int(x) + 1
print(f"x: {x}, y: {y}")
即在两个花括号之间放 表达式
Numbers
除了整数小数,还有 复数
print(10 / 3) # 3.333333
print(10 // 3) # 3
print(10 ** 3) # 10^3
类型转换
由于 input内置函数 返回的是一个字符串
不能将input返回的结果与一个数相加,比如 y = x(由input返回) + 1
type(x)
int(x)
float(x)
bool(x)
str(x)
3、控制流
字符串和字符比较和ASCII码函数
三元运算
age = 22
message = "Eligible" if age >= 18 else "Not Eligible"
逻辑运算符
and
or
not
短路
high_income = False
good_credit = True
student = True
if (high_income or good_credit) and not student:
print("Eligible")
else:
print("Not Eligible")
比较运算符
if 18 <= age < 25:
For循环
for number in range(3):
print("Hello", number, (number + 1) * ".")
Hello 0 .
Hello 1 ..
Hello 2 ...
for number in range(1, 10, 2):
print("Hello", number)
不包括第二个数字
Hello 1
Hello 3
Hello 5
Hello 7
Hello 9
遍历
for x in "Python":
print(x)
for x in [1, 2, 3, 4]:
print(x)
while
number = 100
while number > 0:
print(number)
number //= 2
command = ""
while command.lower() != "quit":
command = input(">>>")
print("ECHO", command)
4、函数
函数下空两行
def greet(name):
return f"Hi {name}"
message = greet("Mosh")
file = open("content.txt", "w")
file.write(message)
参数
def multiply(*numbers):
print(numbers)
multiply(2, 3, 4, 5)
(2, 3, 4, 5)
def multiply(*numbers):
for number in numbers:
print(number)
multiply(2, 3, 4, 5)
字典
def save_user(**user):
print(user)
save_user(id=1, name="John", age=22)
{'id': 1, 'name': 'John', 'age': 22}
def save_user(**user):
print(user["name"]) # John
save_user(id=1, name="John", age=22)
global
在函数中使用global意味着用的是全局变量
message = "a"
def greet():
global message
message = "b"
greet()
print(message) # b
5、数据结构
列表list
python列表中的每个对象都可以是不同类型的
letters = ['a', 'b', 'c']
matrix = [[0, 1], [2, 3]]
zeros = [0] * 100
combined = letters + zeros
numbers = list(range(20))
chars = list("Hello World")
print(chars)
print(len(chars))
letters = ["a", "b", "c", "d"]
letters[0] = "A"
print(letters[-1])
print(letters[0:3])
print(letters[::2]) # ['A', 'c']
numbers = list(range(20))
print(numbers[::-1]) # [19, 18, ..
numbers = [1, 2, 3]
first, second, third = numbers
numbers = [1, 2, 3, 4, 4, 4, 4]
first, second, *other = numbers
print(first) # 1
print(other) # [3, 4, 4, 4, 4]
numbers = [1, 2, 3, 4, 4, 4, 4]
first, *other, last = numbers
enumerate
将一个可遍历的数据对象(如列表、元祖、字典和字符串)组合成一个索引序列,同时列出数据下标和数据(索引 值),一般配合for循环使用
在每次迭代中,这个枚举对象会返回一个元祖
letters = ["a", "b", "c"]
for letter in letters:
print(letter)
letters = ["a", "b", "c"]
for letter in enumerate(letters):
print(letter)
(0, 'a')
(1, 'b')
(2, 'c')
letters = ["a", "b", "c"]
for letter in enumerate(letters):
print(letter[0], letter[1])
0 a
1 b
2 c
letters = ["a", "b", "c"]
items = (0, "a")
index, letter = items
for index, letter in enumerate(letters):
print(index, letter)
增加和删除元素
在python中所有事物都是对象
letters = ["a", "b", "c"]
# Add
letters.append("d")
letters.inset(0, "-")
# Remove
letters.pop()
letters.pop(0)
letters.remove("b")
del letters[0:3]
letters.clear()
寻找列表中某个对象的索引
注意与其他语言不同的是,index函数如果找不到,则会出错,而不是返回-1
因此,我们要先用一个if结合in来判断是否存在于列表中
此外,count函数返回这个列表中有多少个匹配的对象
letters = ["a", "b", "c"]
print(letters.count("a"))
if "a" in letters:
print(letters.index("a"))
列表排序
sort会改变原先列表的排序,sorted不会
numbers = [3, 51, 2, 8, 6]
numbers.sort()
numbers.sort(reverse=True)
print(sorted(numbers))
print(sorted(numbers, reverse=True))
以上是给数字或者字符串排序,那么如果是元祖呢?
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
def sort_item(item):
return item[1]
items.sort(key=sort_item)
print(items)
lamda
像上一个例子中,只写一行不用事先占用一个函数名
何时用:当一个函数只是另一个函数的参数时来用,一次性的
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
items.sort(key=lambda item:item[1])
print(items)
map函数
map可以将一个lambda函数作为迭代对象,在原先的列表中跑
如果我们要得到元祖所有第二个元素
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
prices = []
for item in items:
prices.append(item[1])
print(prices)
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
prices = map(lambda item:item[1], items)
print(prices) # <map object at 0x1055872b0>
for item in prices:
print(item)
或者将map转换成list
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
prices = list(map(lambda item:item[1], items))
print(prices) # [10, 9, 12]
Filter函数
我们想只得到价格大于等于10的
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
filtered = list(filter(lambda item: item[1] >= 10, items))
print(filtered)
map和filter替代
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12),
]
# prices = list(map(lambda item:item[1], items))
prices = [item[1] for item in items]
# filtered = list(filter(lambda item: item[1] >= 10, items))
filtered = [item for item in items if item[1] >= 10]
zip函数
list1 = [1, 2, 3]
list2 = [10, 20, 30]
# [('a', 1, 10), ('b', 2, 20), ('c', 3, 30)]
print(list(zip("abc", list1, list2)))
deque
from collections import deque
queue = deque([])
queue.append(1)
queue.append(2)
queue.append(3)
queue.popleft()
print(queue)
if not queue:
print("Empty")
tuple元祖
不能添加和删除和修改
用()表示
或者如果不加(),光是 point = 1, 2
甚至 point = 1,
注意必须有“,”
point = (1, 2) + (3, 4)
point = (1, 2) * 3
point = tuple([1, 2])
point = tuple("Hello World")
point = (1, 2, 3)
print(point[0])
print(point[0:2])
x, y, z = point
if 10 in point:
print("Exists")
交换两个变量
x = 10
y = 11
x, y = y, x # 利用元祖
a, b = 1, 2 # 赋值
Arrays数组
只有在处理大的数字列表使用,一般不用
比列表快
注意数组中对象类型相同!
查阅 typecode
,决定对象类型
from array import array
numbers = array("i", [1, 2, 3])
numbers[0]
Set
可用于去重
无法按索引取值,如果要,就转成list
numbers = [1, 1, 2, 3, 4]
uniques = set(numbers)
second = {1, 4}
second.add(5)
second.remove(5)
len(second)
print(uniques)
numbers = [1, 1, 2, 3, 4]
first = set(numbers)
second = {1, 5}
print(first | second) # {1, 2, 3, 4, 5}
numbers = [1, 1, 2, 3, 4]
first = set(numbers)
second = {1, 5}
print(first | second) # {1, 2, 3, 4, 5}
print(first & second) # {1}
print(first - second) # {2, 3, 4}
print(first ^ second) # {2, 3, 4, 5}
字典
point = {"x": 1, "y": 2}
# or
point = dict(x=1, y=2)
point["x"] = 10
point["z"] = 20
print(point)
if "a" in point:
print(point["a"])
# or
print(point.get("a", "Not Exists!!!"))
del point["x"]
for key in point:
print(key, point[key])
# or
for x in point.items():
print(x) # 得到tuple
# or
for key, val in point.items():
print(key, val)
values = []
for x in range(5):
values.append(x * 2)
# or
values = [x * 2 for x in range(5)]
而如果是在字典中:
values = []
for x in range(5):
values[x] = x * 2
# or
values = {x: x * 2 for x in range(5)} # dict
Generators生成器
在处理一个真正的大数据集或可能是一个无限的数据流的情况下,使用一个生成器表达式
由于生成器对象不在内存中存储所有的项目,你将无法获得总数
from sys import getsizeof
values = (x * 2 for x in range(1000))
print(values) # <generator object <genexpr> at 0x102f75460>
print("gen:", getsizeof(values)) # gen: 104
for x in values:
print(x)
values = [x * 2 for x in range(1000)]
print("list:", getsizeof(values)) # list: 8856
values = (x * 2 for x in range(1000))
print(len(values)) # TypeError: object of type 'generator' has no len()
Unpacking Operator解包操作符
numbers = [1, 2, 3]
print(numbers) # [1, 2, 3]
print(*numbers) # 1 2 3
values = list(range(5))
print(values) # [0, 1, 2, 3, 4]
values = [*range(5)]
print(values) # [0, 1, 2, 3, 4]
values = [*range(5), *"Hello World"]
print(values) # [0, 1, 2, 3, 4, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
first = [1, 2]
second = [3]
values = [*first, "a", *second, *"hello"] # [1, 2, 'a', 3, 'h', 'e', 'l', 'l', 'o']
print(values)
first = {"x": 1}
second = {"x": 10, "y": 2} # 如果有多个相同key的项目,最后一个
combined = {**first, **second, "z": 1}
print(combined) # {'x': 10, 'y': 2, 'z': 1}
Exercise
sentence = "This is a common interview question"
char_frequency = {}
for char in sentence:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
char_frequency_sorter = sorted(
char_frequency.items(),
key=lambda ky: ky[1],
reverse=True
)
print(char_frequency_sorter)
# [('i', 5), (' ', 5), ('s', 3), ('o', 3), ('n', 3), ('e', 3), ('m', 2), ('t', 2), ('T', 1), ('h', 1), ('a', 1), ('c', 1), ('r', 1), ('v', 1), ('w', 1), ('q', 1), ('u', 1)]
6、Exceptions
try:
age = input("Age:")
except ValueError as ex: # 捕捉异常并输出语句
print("You didn't enter a valid age")
print(ex)
print(type(ex))
else: # 没有异常
print("No exceptions were thrown")
print("Execution continues") # 无异常或捕捉异常
处理不同异常
try:
age = input("Age:")
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age")
else:
print("No exceptions were thrown")
Cleaning up
try:
file = open("app.py")
age = input("Age:")
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age")
else:
print("No exceptions were thrown")
finally: # 无论是否有异常
file.close()
The With Statement
try:
with open("app.py") as file:
print("File opened.")
age = input("Age:")
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age")
else:
print("No exceptions were thrown")
Raising Exceptions
def calculate_xfactor(age):
if age <= 0:
raise ValueError("Age cannot be 0 or less")
return 10 / age
try:
calculate_xfactor(-1)
except ValueError as error:
print(error)
Cost of Raising Exceptions
在编写自己的函数时,最好不要引发异常(快慢)
可以用返回 None, 然后特判的方式
7、Classes类
类的命名规则是 每个单词的首字母大写,但是不使用下划线来区分不同的单词
构造函数
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x}, {self.y})")
point = Point(1, 2)
point.draw()
Class vs Instance Attributes
class Point:
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x}, {self.y})")
Point.default_color = "yellow"
point = Point(3, 4)
print(point.default_color) # yellow
point.draw()
another = Point(3, 4)
print(point.default_color) # yellow
another.draw()
Class vs Instance Methods
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def zero(cls):
return cls(0, 0)
def draw(self):
print(f"Point ({self.x}, {self.y})")
point = Point.zero()
point.draw()