首先我们来了解一下这个问题中应用到的函数
Python enumerate() 函数
enumeeate() 是python中的内置函数,可以直接调用,不用引入。各大python主流网站介绍都差不多
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中 。
Python 2.3. 以上版本可用 ,2.6 添加 start 参数。
语法
以下是 enumerate() 方法的语法:
enumerate(sequence, [start=0])
参数
sequence -- 一个序列 、迭代器或其他支持迭代对象。
start -- 下标起始位置 。
返回值
返回 enumerate(枚举) 对象。
实例
以下展示了使用 enumerate() 方法的实例:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]>>> list(enumerate(seasons, start=1)) # 下标从 1 开始[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通的 for 循环
>>>i = 0>>> seq = ['one', 'two', 'three']>>> for element in seq: ... print i, seq[i]... i +=1... 0 one1 two2 three
for 循环使用 enumerate
>>>seq = ['one', 'two', 'three']>>> for i, element in enumerate(seq): ... print i, element... 0 one1 two2 three
这个问题我们主要是要用到enumeeate() 函数和for循环结合,解决一般处理数据
有个平常办公过程中比较实用的作用
补充:统计文件行数可以这样写:
count=len(open(filepath,'r').readlines()) 这种方法简单,但是可能比较慢 ,当文件比较大时甚至不能工作。 count=0 for index,line in enumerate(open(filepath,'r')): count+=1
————————————————-----------------------------------------------------------
接下来我们来说标题里提到的问题:有一个数组,数组里任意数组合相加为一个固定值,找出这些排列组合的数组具体实例如下
def sum_list(bool_list, n, now_sum): if n >= len(sum_l): return if now_sum + sum_l[n] == sum_num: #如果原有值加上这个值正好为所求的数 bool_list[n] = True #将在bool_list对应的这个数赋值为true for i, j in enumerate(bool_list): if j: print(sum_l[i], end=' ') #输出bool_list中所有对应值为true的值 print('---------------------------') bool_list[n] = True #如果这个数值数被选 sum_list(bool_list, n+1, now_sum+sum_l[n]) #原来的now_sum和加上新的被选值 bool_list[n] = False &本文版权归去快排wWw.seogUrublog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系qq❉61910465