- 博客(7)
- 资源 (1)
- 收藏
- 关注
原创 求质数算法:效率较高
def prime_eratosthenes(n): prime_list = [] #默认True bool_list = [True] * (n + 1) #不是质数为False for i in range(2, n + 1): if bool_list[i]: for j in range(i * i, n + 1, i): bool_list[j] = False #取出质数的索
2020-10-14 15:11:26
169
原创 执行一个字符串表达式:eval() 函数
语法讲解eval() 函数用来执行一个字符串表达式,并返回表达式的值。语法eval(expression[, globals[, locals]])参数expression – 表达式。globals – 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。返回值返回表达式计算结果。实例x=7eval( '3 * x' )#输出21eval('pow(2,2)')#输出4...
2020-10-13 22:36:05
1101
原创 获取列表所有子集:itertools之combinations函数
Python 的itertools库中提供了combinations方法可以轻松的实现排列组合。测试from itertools import combinationstest_data = {'a', 'a', 'a', 'b'}for i in combinations(test_data, 2): print i# 输出('a', 'b')from itertools import combinationstest_data = ['a', 'a', 'a', 'b']fo
2020-09-27 15:29:33
2194
原创 列表最大值与最小值间的元素个数:for循环
def count_range_in_list(li, min, max): ctr = 0 for x in li: if min <= x <= max: ctr += 1 return ctrlist1 = [10, 20, 30, 40, 40, 40, 70, 80, 99]print(count_range_in_list(list1, 40, 100))list2 = ['a', 'b', 'c', 'd'
2020-09-27 15:19:35
330
原创 一个列表是否是其他列表的子列表:is_Sublist
废话不多说,直接上代码def is_Sublist(list_parent, list_child): flag = False if list_child == [] or list_child == list_parent: flag = True elif len(list_child) > len(list_parent): sub_set = False else: for i in range(len(lis
2020-09-27 15:16:17
365
原创 求多个可迭代对象的笛卡尔积:itertools之product函数
product 用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.即:product(A, B) 和 ((x,y) for x in A for y in B)的效果是一样的。使用形式如下:itertools.product(*iterables, repeat=1)iterables 是可迭代对象, repeat指定 iterable 重复几次即:product(A,repeat=3)等价于product(A,A,A)from iterto
2020-09-27 14:41:06
373
原创 从集合中查找最值:max(),min(),nlargest(),nsmallest()
max()、min()入门用法a = [1, 5, 2, 1, 9, 1, 5, 10]print(max(a))print(min(a))#运行结果如下101进阶用法以max()为例来分析。max(interable,key=none),即max()函数中第一个参数需要提供一个可迭代的查找对象。key值为空时,仅返回一个最大值。当key值非空时,max()函数就以key为标准来判断,通常可结合匿名函数使用。a = [14, -57, 21, 10, 19, 12, 25, 10]
2020-09-27 12:47:44
509
空空如也
TA创建的收藏夹 TA关注的收藏夹
TA关注的人