Python中bisect模块管理列表(将列表分级处理或者增加元素并排序)

import bisect

# 查看分数对应的等级
def grade(score, breakpoints=(60, 70, 80, 90), grades='FDCBA'):
    i = bisect.bisect(breakpoints, score)
    return grades[i]


grades_list = [33, 99, 77, 70, 89, 90.5, 100]
ret = [grade(score) for score in grades_list]
print(ret)


"""
    ret =  bisect.bisect(参数1, 参数2)
    参数1: 有序的可迭代对象                                             例:[ 1, 2, 3, 5]
    参数2: 与参数1中的元素类型相似, 参数1中是int类型, 参数2不能使str类型的,   例如: 4
    ret : 参数2如果插到参数1中当做元素 此时的下标作为结果返回.  例: 参数2插入到参数1中, 排第四个, 下标为3,所以ret=3

"""

# 列表中添加新元素并排序
import random

random.seed(1729)   # 固定随机数    https://blog.csdn.net/qq_42327755/article/details/91526175

my_list = [1, 5, 8, 11]
for i in range(5):
    new_item = random.randrange(14)
    bisect.insort(my_list, new_item)
    print(new_item, my_list)
发布了73 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42327755/article/details/91541403