listA = [1, 2, 3, 4]
listA[3] = 10
print(listA)
# [1, 2, 3, 10]
tupleA = (1, 2, 3, 4)
# tupleA[3] = 10
# 执行会报错,'tuple' object does not support item assignment
listA = [1, 2, 3, 4]
listA.append(5)
print(listA)
# [1, 2, 3, 4, 5]
tupleA = (1, 2, 3, 4)
tupleB = (5,6)
# 实际上就是创建了一个新的元组,然后把原来两个元组的值依次填充进去。
print(tupleA+tupleB)
# (1, 2, 3, 4, 5, 6)
l = []
print(l.__sizeof__()) # 40
# 空列表的存储空间为40字节
l.append(1)
print(l.__sizeof__()) # 72
# int类型占用了8字节
# 加入了元素1之后,列表为其分配了可以存储4个元素的空间 (72 - 40)/8 = 4
l.append(2)
print(l.__sizeof__()) # 72
# 由于之前分配了空间,所以加入元素2,列表空间不变
l.append(3)# 72
l.append(4)# 72
l.append(5)
print(l.__sizeof__()) # 104
# 加入元素5之后,列表的空间不足,所以又额外分配了可以存储4个元素的空间,72+32=104
tuple1 = ()
print(tuple1.__sizeof__()) # 24
# 空元组占用24单位空间
tuple2 = (1)
# 等价于tuple2 = 1,不是元组,而是个变量,所以这个是例外
print(tuple2.__sizeof__()) # 28
tuple3 = (1, 2)
print(tuple3.__sizeof__()) # 40,24+8*2=40
tuple4 = (1, 2, 3)
print(tuple4.__sizeof__()) # 48
tuple5 = (1, 2, 3, 4)
print(tuple5.__sizeof__()) # 56
d1 = {'name': 'jason', 'age': 20}#更高效
d = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
print(d1['name']) # jason
print(d1.get('age')) # 20
print('name' in d1) # true
d1['gender'] = 'male' # 增加元素对'gender': 'male'
s1 = {3, 2, 5, 4, 1}
print(2 in s1) # true
s1.add(6)
s1.remove(2)
# 不建议使用pop,集合的 pop() 操作是删除集合中最后一个元素,可是集合本身是无序的,你无法知道会删除哪个元素
s1.pop()
print(sorted(s1)) # [1, 3, 4, 5, 6]
d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}
for k in d: # 遍历字典的键
print(k)
for v in d.values(): # 遍历字典的值
print(v)
for k, v in d.items(): # 遍历字典的键值对
print('key: {}, value: {}'.format(k, v))
entries = [
['--', '--', '--']
[-230273521, 'dob', '1999-01-01'],
['--', '--', '--'],
['--', '--', '--'],
[1231236123, 'name', 'mike'],
['--', '--', '--'],
[9371539127, 'gender', 'male']
]
indices = [None, 1, None, None, 0, None, 2]
entries = [
[1231236123, 'name', 'mike'],
[-230273521, 'dob', '1999-01-01'],
[9371539127, 'gender', 'male']
]
entries[indices[index]]=hashcode-key-value,index是 indices数组的下标索引,对应存储的值是连续的整数,也就是entries的索引。 因为hash code计算出来的很可能是间隔很大的数,比如有两个数,一个计算出来的索引是1,一个计算出来的索引是100万,那么你申请的数组需要100万位。这样造成大量的内存浪费,PyDicMinSize 就是确定一个固定的长度,这样申请资源只申请这么大
每次向字典或集合插入一个元素时,Python 会首先计算键的哈希值(hash(key)),再和 mask = PyDicMinSize - 1 做与操作,计算这个元素应该插入哈希表的位置 index = hash(key) & mask。
Python 会根据哈希值,找到其应该处于的位置;然后,比较哈希表这个位置中元素的哈希值和键,与需要查找的元素是否相等
a = input('a:') # 1
b = input('b:') # 2
print(a + b) # 12,因为是字符串相加
# 第一个参数指定文件位置(相对位置或者绝对位置);
# 第二个参数,如果是 'r' 表示读取,如果是'w' 则表示写入,
# 'rw' ,表示读写都要。
# a 表示追加(append),这样打开的文件,如果需要写入,会从原始文件的最末尾开始写入。
with open('in.txt', 'r') as fin:
all = fin.read()
print(all)
with open('in.txt', 'r') as fin:
text = fin.readline()
while text:
print(text, end='') # 使用end=''参数避免在输出中添加额外的换行符
text = fin.readline()
with open('in.txt', 'w') as fout:
fout.write('hello world')
条件与循环并做一行的复用写法:
x = [1, -2, 3]
y = [value * 2 + 5 if value > 0 else -value * 2 + 5 for value in x]
# 等价于
for value in x:
if value > 0:
y.append(value * 2 + 5)
else:
y.append(-value * 2 + 5)
print(y)
try:
s = input('输入两个数字,用英文逗号隔开:')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except ValueError as err:
print('Value Error: {}'.format(err))
print('continue')
#这里只捕获了ValueError,如果输入1,就会出现IndexError,程序会终止运行
try:
s = input('输入两个数字,用英文逗号隔开:')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except ValueError as err:
print('Value Error: {}'.format(err))
except IndexError as err:
print('Index Error: {}'.format(err))
except Exception as err:
print('Other error: {}'.format(err))
finally:
print('finally')
print('continue')
不太常用,一般有两个目的:
def factorial(input):
# 对输入进行校验,但是放在内嵌函数外,这样的话递归的时候不用反复校验
if not isinstance(input, int):
raise Exception('input must be an integer.')
if input < 0:
raise Exception('input must be greater or equal to 0')
def inner_factorial(input):
if input <= 1:
return 1
return input * inner_factorial(input - 1)
return inner_factorial(input)
print(factorial(5))
MIN_VALUE = 1
MAX_VALUE = 10
def validation_check():
global MIN_VALUE # 不声明的话,会报错
MIN_VALUE += 1
validation_check()
print(MIN_VALUE) # 2
def outer():
x = "local"
print(x)
def inner():
nonlocal x # nonlocal关键字表示这里的x就是外部函数outer定义的变量x
x = 'nonlocal'
print(x)
inner()
outer()
def nth_power(exponent):
def exponent_of(base):
return base ** exponent
return exponent_of # 返回值是exponent_of函数
square = nth_power(2) # 计算一个数的平方,可以理解square是exponent_of(base)的一个函数
print(square(2)) # 计算2的平方
print(square(3)) # 计算3的平方
print(square(4)) # 计算4的平方
def nth_power(base, exponent):
return base ** exponent
print(nth_power(2, 2)) # 计算2的平方
print(nth_power(3, 2)) # 计算3的平方
print(nth_power(4, 2)) # 计算4的平方
print([(lambda x: x * x)(x) for x in range(10)])
# 输出[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
l = [(1, 20), (3, 0), (9, 10), (2, -1)]
l.sort(key=lambda x: x[1]) # 按列表中元组的第二个元素排序
print(l)
# 输出[(2, -1), (3, 0), (9, 10), (1, 20)]
from functools import reduce
l1 = [1, 2, 3, 4, 5]
# map(function, iterable)
new_list1 = map(lambda x: x * 2, l1)
for i in new_list1:
print(i)
# [2, 4, 6, 8, 10]
l2 = [1, 2, 3, 4, 5]
new_list2 = filter(lambda x: x % 2 == 0, l2)
for i in new_list2:
print(i)
# [2,4]
l3 = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, l3) # 5*(4*(3*(2*1))) = 120
print(result) # 120
class Student:
# 用全大写定义一些静态常量
COMPANY = 'zingfront'
def __init__(self, name, age):
print('init function called')
self.name = name
self.__age = age
# 类函数,需要也必须传入cls,通常用于实现不同的init
@classmethod
def create_empty_student(cls, name):
return cls(name, age=18)
# 静态函数,就是一种普通函数,只是在对象内
@staticmethod
def get_company(context):
return Student.COMPANY+context
# 成员函数,常见的就是set 和 get
def get_age(self):
print(self.__age)
def get_name(self):
print(self.name)
stu = Student('tangyong', 26)
stu.get_age() # 私有属性无法再函数外面打印出来的
stu1 = Student.create_empty_student('wangjun')
stu1.get_age() # 默认18
class Animal:
def __init__(self, atype):
self.atype = atype
def print_atype(self):
print(self.atype)
class Dog(Animal):
def __init__(self, name, size):
Animal.__init__(self, 'dog')
self.name = name
self.size = size
def print_all(self):
print(self.name, self.size, self.atype)
class Cat(Animal):
def __init__(self, name, age):
Animal.__init__(self, 'cat')
self.name = name
self.age = age
def print_all(self):
print(self.name, self.age, self.atype)
dog1 = Dog('tom', 20)
cat1 = Cat('jimmy', 30)
dog1.print_all()
cat1.print_all()
dog1.print_atype() # 可以调用父类的函数