"""
针对列表的自定义工具
"""
class ListHelper:
@staticmethod
def last(target, func):
"""
返回满足条件的最后一个值
:param target:
:param func:
:return:
"""
target = target[::-1]
for item in target:
if func(item):
return item
@staticmethod
def sum(target, func):
"""
获取满足条件的对象总数
:param target:
:param func:
:return:
"""
count = 0
for item in target:
if func(item):
count += 1
return count
@staticmethod
def have(target, func):
"""
判断列表中是否包含某个元素
:param target:
:param func:
:return:
"""
for item in target:
if func(item):
return True
return False
@staticmethod
def delete(target,func):
"""
删除元素数量
:param target:
:param func:
:return:
"""
count = 0
for i in range(len(target)-1,-1,-1):
if func(target[i]):
del target[i]
count += 1
return count
@staticmethod
def get_max(target,func):
"""
# 获取满足条件的最大值
:param target:
:param func:
:return:
"""
max_value = target[0]
for i in range(1,len(target)):
if func(max_value) < func(target[i]):
max_value = target[i]
return max_value
@staticmethod
def get_up(target,func):
"""
根据指定条件升序排列
:param target:
:param func:
:return:
"""
for i in range(len(target)-1):
for j in range(i+1,len(target)):
if func(target[i]) > func(target[j]):
target[j],target[i] = target[i],target[j]
return target
@staticmethod
def find_all(target,func_condition):
"""
查找列表中满足条件的所有元素
:param target: 列表
:param func_condition: 条件
函数/方法类型
-- 参数:列表中的元素
-- 返回值:是否满足条件bool值
:return:
"""
for item in target:
if func_condition(item):
yield item
@staticmethod
def first(target,func_condition):
"""
查找列表中满足条件的第一个元素
:param target:
:param func_condition:
:return:
"""
for item in target:
if func_condition(item):
return item
@staticmethod
def select(target,func_condition):
"""
筛选列表中指定条件的数据
:param target:
:param func_condition:
:return:
"""
for item in target:
# yield xxx(item)
yield func_condition(item)
@staticmethod
def get_sum(target,func_condition):
"""
计算列表中指定条件的所有元素和
:param target:
:param func_condition:
:return:
"""
sum_value = 0
for item in target:
# sum_value += xxx(item)
sum_value += func_condition(item)
return sum_value
@staticmethod
def get_min(target,func):
"""
取符合列表的最小值
:param target:
:param func:
:return:
"""
min_value = target[0]
for i in range(1,len(target)):
if func(min_value) > func(target[i]):
min_value = target[i]
return min_value
@staticmethod
def get_down(target,func):
"""
把列表降序
:param target:
:param func:
:return:
"""
for i in range(len(target)-1):
for j in range(i+1,len(target)):
if func(target[i]) < func(target[j]):
target[i],target[j] = target[j],target[i]
return target
@staticmethod
def get_all(target,func):
"""
万能排序
:param target:
:param func:
:return:
"""
for i in range(len(target) - 1):
for j in range(i + 1, len(target)):
if func(target[i], target[j]):
target[i],target[j] = target[j],target[i]
return target
python列表自定义工具
最新推荐文章于 2025-03-06 14:00:34 发布