20210223部分代码记录(python)
程序员文章站
2022-04-28 20:40:40
# 容器 Listxs = [3, 1, 2]print(xs, xs[2])print(xs[-1])xs[2] = 'foo'print(xs)xs.append('bar')print(xs)x = xs.pop()print(x, xs)# 切片slicingnums = list(range(5)) print(nums) print(nums[2:4])print(nums[2:])print(nums[:2])print(num...
# 容器 List
xs = [3, 1, 2]
print(xs, xs[2])
print(xs[-1])
xs[2] = 'foo'
print(xs)
xs.append('bar')
print(xs)
x = xs.pop()
print(x, xs)
# 切片slicing
nums = list(range(5))
print(nums)
print(nums[2:4])
print(nums[2:])
print(nums[:2])
print(nums[:])
print(nums[:-1])
nums[2:4] = [8, 9]
print(nums)
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)
# dictionary 类似Map哈希表
d = {'cat': 'cute', 'dog': 'furry'}
print(d['cat'])
print('cat' in d)
d['fish'] = 'wet'
print(d['fish'])
# print(d['monkey']) # KeyError: 'monkey' not a key of d
print(d.get('monkey', 'N/A'))
print(d.get('fish', 'N/A'))
del d['fish']
print(d.get('fish', 'N/A'))
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal, legs))
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
print('A %s has %d legs' % (animal, legs))
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)
# Set 集合,不同元素的无序集合
animals = {'cat', 'dog'}
print('cat' in animals) # 是否存在
print('fish' in animals)
animals.add('fish')
print('fish' in animals)
print(len(animals))
animals.add('cat')
print(len(animals))
animals.remove('cat')
print(len(animals))
# 与列表相似
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)
# Tuples 不可变的, 可以用作字典中的键和集合的元素
d = {(x, x + 1): x for x in range(10)}
t = (5, 6)
print(type(t))
print(d[t])
print(d[(1, 2)])
# 函数
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print(sign(x))
# 可选参数
def hello(name, loud=False):
if loud:
print('HELLO, %s!' % name.upper())
else:
print('Hello, %s' % name)
hello('Bob')
hello('Fred', loud=True)
class Greeter(object):
def __init__(self, name, Class):
self.name = name
self.Class = Class
def greet(self, loud = False):
if loud:
print("HELLO,%s, %s" %(self.name.upper(), self.Class))
else:
print("Hello,%s" %self.name)
g = Greeter("Fred", "kk")
g.greet()
g.greet(loud = True)
# Numpy
import numpy as np
a = np.array([1, 2, 3]) # (3,)
#a = np.array([[1], [2], [3]]) #(3, 1)
print(type(a))
print(a.shape)
print(a[0], a[1], a[2])
a[0] = 5
print(a)
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b.shape)
print(b[0, 0], b[0, 1], b[0, 2])
a = np.zeros((2, 2))
print(a)
b = np.ones((1, 2))
print(b)
c = np.full((2,2), 7)
print(c)
d = np.eye(2)
print(d)
e = np.random.random((2, 2))
print(e)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
b = a[ : 2, 1 : 3]
print(b)
# 修改切片即修改本身
print(a[0, 1])
b[0, 0] = 77
print(a[0, 1])
#一种索引
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a)
b = np.arange(3)
print(a[b, b])
#布尔索引
a = np.array([[1, 2], [3, 4], [5, 6]])
print(a)
bool_idx = (a > 2)
print(bool_idx)
print(a[bool_idx])
print(a[a > 2])
x = np.array([1, 2]) # Let numpy choose the datatype
print(x.dtype) # Prints "int64"
x = np.array([1.0, 2.0]) # Let numpy choose the datatype
print(x.dtype) # Prints "float64"
x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
print(x.dtype) # Prints "int64"
print(type(x))
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
print(x + y)
print(np.add(x, y))
print(x - y)
print(np.subtract(x, y))
print(x * y)
print(np.multiply(x, y))
print(x / y)
print(np.divide(x, y))
print(np.sqrt(x))
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
# [43 50]]
print(x.dot(y))
print(np.dot(x, y))
a = np.array([[1, 2], [3, 4]])
print(np.sum(a))
print(np.sum(a, axis = 0))
print(np.sum(a, axis = 1))
print(a.T)
# Note that taking the transpose of a rank 1 array does nothing:
v = np.array([1,2,3])
print(v) # Prints "[1 2 3]"
print(v.T) # Prints "[1 2 3]"
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x) # Create an empty matrix with the same shape as x
for i in range(4):
y[i, :] = x[i, : ] + v
print(y)
#堆叠向量成矩阵,避免显式循环耗时
vv = np.tile(v, (4, 1))
print(vv)
y = x + vv
print(y)
# Numpy广播允许我们执行此计算而无需实际创建多个副本v。考虑这个版本,使用广播:
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v # Add v to each row of x using broadcasting
print(y)
# Compute outer product of vectors
v = np.array([1,2,3]) # v has shape (3,)
w = np.array([4,5]) # w has shape (2,)
print(np.reshape(v, (3, 1)) * w)
x = np.array([[1,2,3], [4,5,6]])
print(x + v)
print((x.T + w).T)
print(x + np.reshape(w, (2, 1)))
print(x * 2, "------------")
from imageio import imread, imsave
from PIL import Image
#from scipy.misc import imresize
img = imread("whq.JPG")
print(img.dtype, img.shape)
img_m = img * [1, 0.95, 0.9]
#print(img_m.dtype, img_m.shape) # float64 (370, 250, 3)
img_m = np.array(Image.fromarray(np.uint8(img_m)).resize((300, 300)))
#img_m = imsave(img_m, )
imsave('kk.jpg', img_m)
# 点之间的距离
from scipy.spatial.distance import pdist, squareform
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
d = squareform(pdist(x, 'euclidean'))
print(d)
# Matplotlib
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()
plt.subplot(2, 1, 1)
plt.plot(x, y_sin)
plt.title("Sine")
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title("Cos")
plt.show()
from imageio import imread, imsave
from PIL import Image
img = imread("whq.JPG")
img_m = img * [1, 0.95, 0.9]
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.subplot(1, 2, 2)
plt.imshow(np.uint8(img_m))
plt.show()
import numpy as np
def add(x, y, f):
return f(x) + f(y)
print(add(1, -2, np.sin))
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
def add(x, y):
return x + y
from functools import reduce
print(reduce(add, [1, 2, 3, 4, 5]))
def normalize(name):
return name.title()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
a = [3, -2, 1]
b = sorted(a)
b = sorted(a, key = abs)
print(b)
sorted(['bob', 'about', 'Zoo', 'Credit'])
sorted(['bob', 'about', 'Zoo', 'Credit'], key = str.lower)
sorted(['bob', 'about', 'Zoo', 'Credit'], key = str.lower, reverse = True)
sorted(['bob', 'about', 'Zoo', 'Credit'], reverse = True)
def product(*nums):
sum = 1
for num in nums:
sum *= num
return sum
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('测试失败!')
elif product(5, 6) != 30:
print('测试失败!')
elif product(5, 6, 7) != 210:
print('测试失败!')
elif product(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
try:
product()
print('测试失败!')
except TypeError:
print('测试成功!')
def trim(s):
if s[:1] != " " and s[-1:] != " ":
return s
elif s[ : 1] == " ":
return trim(s[1 : ])
else:
return trim(s[ : -1])
if trim('hello ') != 'hello':
print('测试失败1!')
elif trim(' hello') != 'hello':
print('测试失败2!')
elif trim(' hello ') != 'hello':
print('测试失败3!')
elif trim(' hello world ') != 'hello world':
print('测试失败4!')
elif trim('') != '':
print('测试失败5!')
elif trim(' ') != '':
print('测试失败6!')
else:
print('测试成功!')
mi =1e9
ma = -1e9
def findMinAndMax(L):
global mi, ma
for l in L:
mi = min(mi, l)
ma = max(ma, l)
return (mi, ma)
print(findMinAndMax([1,2,3,4,5,6,7,8,9]))
print(mi, ma)
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() if isinstance(s, str) else s for s in L1] # if else表达式
L3 = [s.lower() for s in L1 if isinstance(s, str)] # if过滤
print(L2, L3)
# 生成器 边循环边计算,保存的是算法 [] -> ()
L = (x ** 2 for x in range(10))
print(next(L))
print(next(L),"-----")
for i in L:
print(i)
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
o = odd()
next(o)
next(o)
next(o)
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
for i in fib(6):
print(i)
f = fib(6)
print(f)
g = fib(6)
while True:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
# 杨辉三角生成器
def triangles():
L = [1]
while True:
yield L
L = [L[i] + L[i + 1 ] for i in range(len(L) - 1 ) ] #先生成除首位的数字
L.insert(0, 1) #list开头添加 1
L.append(1) #list结尾添加 1
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
t = triangles()
print(next(t))
print(next(t))
print(next(t))
print(next(t))
def ziran():
a = 1
while True:
yield a
a += 1
zz = ziran()
print(next(zz))
print(next(zz))
print(next(zz))
from collections.abc import Iterable
from collections.abc import Iterator
print(isinstance([], Iterable))
print(isinstance("abc", Iterator))
print(isinstance(iter('abc'), Iterator))
#凡是可作用于for循环的对象都是Iterable类型;
#凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列
#集合数据类型如list、dict、str等是Iterable但不是Iterator
#不过可以通过iter()函数获得一个Iterator对象。
class Student(object):
pass
bart = Student()
bart.name = "whq"
print(bart.name)
class Stu(object):
def __init__(self, name, age):
self.__name = name
self.__age = age
def print_stu(self):
print("%s : %d" %(self.__name, self.__age))
bart = Stu("Michael", 12)
#print(bart.__name, bart.__age) #private 错误
#print(bart._Stu__name)
# 不建议,private实现机制,python解释器对外将变量名改变从而无法访问
bart.print_stu()
# 继承和多态
class Animal(object):
def run(self):
print("Animal is running----")
class Dog(Animal):# 可直接代码复用pass也行,也可重新定义函数进行覆盖
def run(self):
print("the dog is running---")
class Timer(object):
def run(self):
print('Start...')
a = Animal()
dog = Dog()
dog.run()
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(isinstance(a, Dog)) # False 子类可判断为父类,父类不能判断为子类
# type() 得到直接对应的类
print(type(a))
print(type(dog))
def run_twice(Animal):
Animal.run()
Animal.run()
# 传入实例
run_twice(Animal())
run_twice(Dog())
run_twice(Timer()) # python动态语言:不一定是Animal类型,有run()方法即可 java静态
# 对于一个变量,我们只需要知道它是Animal类型,无需确切地知道它的子类型
# 就可以放心地调用run()方法,而具体调用的run()方法是作用在Animal、Dog对象上
# 由运行时该对象的确切类型决定,这就是多态真正的威力
print(isinstance([1, 2, 3], (list, tuple))) # 其中一种
print(isinstance((1, 2, 3), (list, tuple)))
# 总结:总是优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。
dir("ABC")
#print(dir("ABC"))
print(len("ABC"), "ABC".__len__())
class Student1(object):
name = "Student"
s = Student1()
print(s.name) # Student 类属性
s.name = "Michael"
print(s.name) # Michael 屏蔽类属性,用实例属性
t = Student1()
print(t.name) # Student
del s.name
print(s.name) # Student 类属性
try:
print('try...')
r = 10 / int('a') # r = 10 / int('a', 16) # ok
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
本文地址:https://blog.csdn.net/whq___/article/details/113998270
下一篇: 杨桃如何挑选,该怎么食用