基础: 总结及demo示例
Python数组和列表有什么区别
Python中的数组和列表具有相同的存储数据方式。但是,数组只能包含单个数据类型元素,而列表可以包含任何数据类型元素
Python中的函数是什么?
函数是一个代码块,只有在被调用时才会执行。要定义Python函数,请使用def关键字
__init__是什么?
__init__是Python中的方法或构造函数。在创建类的新对象/实例时,将自动调用此方法来分配内存。所有类都有__init__方法。
什么是lambda函数?
匿名函数称为lambda函数。此函数可以包含任意数量的参数,但只能有一个语句
a = lambda x,y : x+y
print(a(5, 6)) # 结果 11
Python中的self是什么?
Self是类的实例或对象。在Python中,这显然包含在第一个参数中, __init__方法中的self变量引用新创建的对象,而在其他方法中,它引用其方法被调用的对象
如何 break, continue and pass work
方法及属性 | 说明 |
---|---|
break | 当满足某些条件并且控制转移到下一个语句时允许循环终止。 |
continue | 允许在满足某些特定条件时跳过循环的某些部分,并将控件转移到循环的开头 |
pass | 在语法上需要一些代码块时使用,但是你想跳过它的执行。这基本上是一个空操作。执行此操作时没有任何反应。 |
[:: - 1}是什么?
[:: - 1]用于反转数组或序列的顺序。
import array as arr
My_Array=arr.array('i',[1,2,3,4,5])
My_Array[::-1]
# 输出:数组('i',[5,4,3,2,1])
#[:: - 1]重新打印有序数据结构的反转副本,例如数组或列表。原始数组或列表保持不变。
# 检查类型
from types import FunctionType, MethodType
with
with 管理的时候进入是 __enter__方法,退出之后走__exit__方法
partial偏函数
#偏函数的第二个部分(可变参数),按原有函数的参数顺序进行补充,参数将作用在原函数上,最后偏函数返回一个新函数
from functools import partial
def test(a,b,c,d):
return a+b+c+d
tes=partial(test,1,2)
print(tes(3,4))
demo-示例
随机验证码
def xxx(number=4):
it = []
while len(it) < number:
idef = str(random.choice(
[random.randint(0, 9), chr(random.choice([random.randint(65, 90), random.randint(97, 122)]))]))
it.append(idef)
return ''.join(it)
print(xxx(3))
def get_random_num():
# 生成一个随机数组
randomnum = [random.choice([chr(random.randint(65, 90)),
chr(random.randint(97, 122)),
str(random.randint(0, 9))]) for i in range(5)]
# 去掉小数点
strnum = ''.join(randomnum)
return strnum
x=[random.choice([chr(random.randrange(97,122)), str(random.randint(0,9)), chr(random.randrange(65,90))]) for i in range(4)]
y=""
print(y.join(x)) # l45u
x=''.join([random.choice([chr(random.randrange(97,122)), str(random.randint(0,9)), chr(random.randrange(65,90))]) for i in range(4)]) # 结果 g438
循环目录-os
遍历目录,然后yieid返回单个文件判断
def delete_log(self):
for server_list in setting.BASE_LOG:
get_file = FileUtil.File_List(server_list)
# 生成器 循环获取到的 文件列表 如 E:\mqtt\server\log\2019-06-14-6.log
for next_file in get_file.scanFile():
# 生成一个时间对象
file = DateUtil.GetDate(next_file)
# 获取时间结果, 当获取到的时间大于3,也就说明时间大于3天,直接给它删除
if file.get_Time() >= 3:
os.remove(next_file)
# fileUtil
import os
class File_List(object):
'''
获取文件目录如 E:\t3\practice\mqttCheck\log
使用 os.scandir 生成器遍历这个目录
curSubEntry.is_file 如果是文件, 那么就直接用生成器的文件返回这个文件, 一次取一个
'''
def __init__(self, getFile):
self.getFile = getFile
def scanFile(self):
with os.scandir(self.getFile) as dirEntryList:
# 打开这个生成器, 然后循环这个目录,并判断是文件还是目录
for curSubEntry in dirEntryList:
if curSubEntry.is_file():
# 如果是文件, 那就用生成器给它返回
__baseFile = yield os.path.join(self.getFile, curSubEntry)
sorted
IP地址排序
t3 = ['192.168.1.33', '10.5.2.4', '10.5.1.3', '202.98.96.68', '133.120.1.1', '192.168.1.22']
print(sorted(t3, key=lambda x: (int(x.split('.')[0]), int(x.split('.')[1]), int(x.split('.')[2]) )))
['10.5.1.3', '10.5.2.4', '133.120.1.1', '192.168.1.33', '192.168.1.22', '202.98.96.68]
列表加元组地址排序
t1 = [(1, '192.168.1.100'), (2, '192.168.1.101'), (3, '192.168.1.2'), (4, '192.168.1.3')]
print(sorted(t1, key=lambda x: (int(x[1].split('.')[0]), int(x[1].split('.')[1]), int(x[1].split('.')[2]), int(x[1].split('.')[3]))))
# [(3, '192.168.1.2'), (4, '192.168.1.3'), (1, '192.168.1.100'), (2, '192.168.1.101')]
# 拆分说明
sorted(t1, key=lambda x: x[1]) # 给列表中元组第二个值进行排序
sorted(t1, key=lambda x: (int(x[1].split('.')[0])) # 给二个值的第一个分割的值排序 如192
# 后续就是依次的 192 [0] 168 [1] 1 [2] 数字 [3]
replace
# 如果 find & 大于0说明有多个值,直接返回None, 否则就切割它 然后取?xxx =inmaps的结果值 inmaps
tablename = show.replace("?", "").split("=")[1] if show.find("&") < 0 else None
divmod
divmod(10,3): 对整数部分取余,结果是一个元组.(3,1,)
all
判断 为空 的工厂函数
# all([])只有当列表里的元素都有值(不为none/0/空字符串)的时候,才会返回true
if not all([author, book]): # 与下边对面结果是一样的
# if author == "" or book == "":
sql_list = []
for seq in seqid:
# 如果添加不成功,只有两种可能 序号存在或 序列ID存在
sql = 'select * from firewalld where {0} = "{1}"'.format(seq, data[seq])
# all 有值为true, 无值为false
if all([db.session.execute(sql).fetchall()]):
sql_list.append(seq)
# 有值为false, 无值的时候为true
return False if all([sql_list]) else True
1、判断列表(list)中所有元素是否在集合(set)中
list_string = ['big', 'letters']
string_set = set(['hello', 'hi', 'big', 'cccc', 'letters', 'anotherword'])
result = all([word in string_set for word in list_string])#结果是True
2、判断列表中的每个字符串元素是否含另一个列表的所有字符串元素中
list_string= ['big', 'letters']list_text = ['hello letters', 'big hi letters', 'big superman letters']result = all([word in text for word in list_string for text in list_text]) #结果是False,因为'big'不在'hello letters'中。
3、如果要获取符合条件字符串,可以用filter
list_string= ['big', 'letters']list_text = ['hello letters', 'big hi letters', 'big superman letters']all_words = list(filter(lambda text: all([word in text for word in list_string]), list_text ))
print(all_words) #['big hi letters', 'big superman letters']