Python知识点(一)

                                              Python知识点(一)

lambda函数

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 = "https://mp.csdn.net/postedit/82865219"
>>>array = re.findall(r"pos", text)

['pos']
  • ^:匹配以^标识开头的字符串
  • $:匹配以$标识结束的字符串
>>>import re
>>>text1 = "https://mp.csdn.net  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 = "https://mp.csdn.net/postedit/82865219"
>>>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'>: ['https://mp.csdn.net/postedit/']

猜你喜欢

转载自blog.csdn.net/jly164260234/article/details/82865219