1. 进制转换
a = 12 # 十进制的数字12
print(bin(a)) # 0b1100 使用bin内置函数可以将数字转换成为二进制
print(oct(a)) # 0o14 使用oct内置函数可以将数字转换成为八进制
print(hex(12)) # 0xc 使用hex内置函数可以将数字转换成为十六进制
2. 运算符的优先级
print(10 + 2 * 3 ** 2) # 28
# 逻辑运算的优先级: not > and > or
print(True or False and True) # True and True ==> True
print(False or not False) # False or True ==> True
print(True or True and False) # True or True ==> True
# 强烈建议:在开发中,使用括号来说明运算符的优先级
print(True or True and False) # True
print(True or (True and False))
# 逻辑运算符规则:
# 逻辑与运算:
# 只要有一个运算数是False,结果就是False;只有所有的运算数都是True,结果才是True
# 短路:只要遇到了False,就停止,不再继续执行了
# 取值:取第一个为False,如果所有的运算数都是True,取最后一个运算数
# 逻辑或运算:
# 只要有一个运算数是True,结果就是True;只有所有的运算数都是False,结果才是False
# 短路:只要遇到了True,就停止,不再继续执行了
# 取值:取第一个为True的值,如果所有的运算数都是False,取最后一个运算数
a = 23
print(type(a))
3. 列表推导式
# 列表推导式作用是使用简单的语法创建一个列表
nums = [i for i in range(10)]
print(nums)
x = [i for i in range(10) if i % 2]
print(x)
# points 是一个列表。这个列表里的元素都是元组
points = [(x, y) for x in range(5, 9) for y in range(10, 20)]
print(points)
# 了解即可
# 请写出一段 Python 代码实现分组一个 list 里面的元素,比如 [1,2,3,...100]变成 [[1,2,3],[4,5,6]....]
m = [i for i in range(1, 101)]
print(m)
# m[0:3] j ==> 0
# m[3:6] j ==> 3
# j ==> 6
n = [m[j:j + 3] for j in range(0, 100, 3)]
print(n)
4. 深拷贝与浅拷贝
import copy
# 浅复制(拷贝)
nums = [1, 2, 3, 4, 5]
nums1 = nums # 深拷贝/浅拷贝?都不是,是一个指向,是赋值
nums2 = nums.copy() # 浅拷贝,两个内容一模一样,但是不是同一个对象
nums3 = copy.copy(nums) # 和 nums.copy()功能一致,都是浅拷贝
# 深拷贝,只能使用copy模块实现
words = ['hello', 'good', [100, 200, 300], 'yes', 'hi', 'ok']
# words1是words的浅拷贝
# 浅拷贝认为只拷贝了一层
# words1 = words.copy()
# 深拷贝的words2
words2 = copy.deepcopy(words)
words[0] = '你好'
print(words2)
words[2][0] = 1
print(words2)
5. 赋值运算符的特殊使用场景
# 等号连接的变量可以传递赋值
a = b = c = d = 'hello'
print(a, b, c, d)
# x = 'yes' = y = z
m, n = 3, 5 # 拆包
print(m, n)
x = 'hello', 'good', 'yes'
print(x) # ('hello', 'good', 'yes')
# 拆包时,变量的个数和值的个数不一致,会报错
# y, z = 1, 2, 3, 4, 5
# print(y, z)
# o, p, q = 4, 2
# print(o, p, q)
# * 表示可变长度
# o, *p, q = 1, 2, 3, 4, 5, 6
# print(o, p, q) # 1 [2, 3, 4, 5] 6
# *o, p, q = 1, 2, 3, 4, 5, 6
# print(o, p, q) # [1, 2, 3, 4] 5 6
o, p, *q = 1, 2, 3, 4, 5, 6
print(o, p, q) # 1 2 [3, 4, 5, 6]
6. 情人节表白代码
import numpy as np
import matplotlib.pyplot as plt
# 生成x坐标 -2到2范围 的 等差数列数组,数组元素一共1500个
x = np.linspace(-2, 2, 1500)
# 上半部分爱心函数线段
y1 = np.sqrt(1 - (np.abs(x) - 1) ** 2)
# 下半部分爱心函数线段
y2 = -3 * np.sqrt(1 - (np.abs(x) / 2) ** 0.5)
# fill_between是填充线段内部的颜色
plt.fill_between(x, y1, color='red')
plt.fill_between(x, y2, color='red')
# 控制x轴的范围
plt.xlim([-2.5, 2.5])
# 生成文本,指定文本位置 ,字体大小
plt.text(0, -0.4, 'I love you!', fontsize=30, fontweight='bold', color='yellow', horizontalalignment='center')
# 去除刻度
plt.axis('off')
plt.show()
(日常美图时间)