Python知识点(一)

lambda函数、列表推到式、文件的简单处理(写和读都是以字符串的格式)、re.findall的用法、format的用法、异常处理、随机函数的使用、时间函数的使用

1.lambda函数:不能含有命令,同时表达式不能超过一个;可以替换一个简单的函数

k = lambda x, y: x**3 + y
print(k)#返回的是地址
print(k(2, 4))


<function <lambda> at 0x0000021288449598>
12

2.列表推导式

  • 列表推导式是用来创建和操作列表的一种方式
  • 列表推导式由一个表达式以及紧跟这个表达式的for语句构成,for语句还可以跟0个或多个if或for语句
>>>lst1 = [1, 2, 3]
>>>lst2 = [3, 4, 5]
>>>[x * y for x in lst1 for y in lst2]

[3, 4, 5, 6, 8, 10, 9, 12, 15]


>>>[x for x in lst1 if 4 > x > 1]

[2, 3]

3.文件的简单处理(写和读都是以字符串的格式)

# write
with open("test.txt", "wt") as out_file:
      out_file.write("改文本会写入到文件中\n看到我了吧!")

# read
with open("test.txt", "rt") as in_file:
      text = in_file.read()

print(text)

4.re.findall的用法

在import re中,(re.findall(pattern, string, flags=0)):返回string中所有与pattern相匹配的全部字符串,得到数组

  • r:查找string中出现r标识的字串
>>>import re
>>>text = ""
>>>array = re.findall(r"pos", text)

['pos']
  • ^:匹配以^标识开头的字符串
  • $:匹配以$标识结束的字符串
>>>import re
>>>text1 = "  wwww "
>>>text2 = "blog.csdn.net"
>>>array1 = re.findall(r"^https", text1)
   array2 = re.findall(r"^https", text2)
   array3 = re.findall(r"$net", text1)
   array4 = re.findall(r"$net", text2)

array1 = ['https']
array2 = []
array3 = []
array4 = ['net']
  • []:匹配括号中的其中一个字符
>>>import re
>>>text = "I am so happy! "
>>>array1 = re.findall("[a-zA-Z]", text)
   array2 = re.findall("[a-zA-Z]+", text)

array1 = ['I', 'a', 'm', 's', 'o', 'h', 'a', 'p', 'p', 'y']
array2 = ['I', 'am', 'so', 'happy']
  • \d:匹配0到9之间的数字
  • \D:匹配除0到9之外的字符
>>>import re
>>>text = ""
>>>array1 = re.findall("\d", text)
   array2 = re.findall("\d\d", text)
   array3 = re.findall("\D", text)
   array4 = re.findall("\D+", text)

array1 = ['8', '2', '8', '6', '5', '2', '1', '9']
array2 = ['82', '86', '52', '19']
array3 = ['h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'p', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't', '/', 'p', 'o', 's', 't', 'e', 'd', 'i', 't', '/']
array4 = <class 'list'>: ['/postedit/']

5.format的用法

print("{0:=^20}".format("PYTHON"))  顺序:<填充><对齐<左^中>右><宽度>
print("{0:,.f}".format(12345.678))  顺序:<千位分隔符><精度><类型b,c,d,o,x,X,e,E,f,%>

6.异常处理

#异常处理
try:

except NameError: # 异常类型名称

else: # 不发生异常时执行

finally: # 对应语句块一定会执行

7.随机函数

import random  # 随机函数库

random.seed(10)  # 产生种子10对应的随机数
k = random.random()  # 产生一个[0.0,1.0)的随机小数
print(k)
# random.randint(a, b) 产生一个[a, b]之间的随机整数
# random.randrange(m,n,k) [m, n)步长为k的随机整数
# random.getrandbits(k) 产生一个k比特长的随机整数
# random.uniform(a,b)  [a, b] 生产一个随机小数
# random.choice(seq) 从列表中随机选择一个元素
# random.shuffle(seq)  从序列中的元素随机排列,返回打乱后的序列
# random.sample(seq,k) 从序列中随机获得k个长度的序列

8.时间函数的使用

import time
print(time.time()) #秒
print(time.ctime()) #人们可读取的字符串时间,当前时间
t = time.gmtime() #计算机可处理的格式,time格式
k = time.strftime("%Y-%m-%d %H:%M:%S", t) #时间格式化
#%Y 年份; %m 月份(数字); %B 月份; %b 月份缩写; %d 日期; %A 星期
#%a 星期缩写; %H 24小时制时间; %h 12小时制的时间; %p 上下午; %M 分钟; %S 秒
z = time.strptime(k, "%Y-%m-%d %H:%M:%S")
start = time.perf_counter()
end = time.perf_counter()
#print(end - start)
#time.sleep(s) 程序停滞s秒