【python】combinations函数遍历列表内元素不同组合

在参数调优的过程中,不同个体数的样本组合需要计算,但是一个一个用for来穷尽组合的可能显得太过笨拙,查到可以用itertools中的combinations模块来处理类似的问题:

from itertools import combinations
from sys import argv
import os

lst=[]

with open(argv[1], "r") as fi:
    for lines in fi.readlines():
        line = lines.strip("\n")
        lst.append(line)
for j in range(9):
    comlst = list(set(combinations(lst,j)))
    for i in comlst:
        filename = "allcombine_"+str(j)+"_combine_"+str(comlst.index(i))+"_.bed"
        for k in i:
            print(k)
            os.system('cat {} >> tmp/{}'.format(k,filename))
            os.system('bedtools sort -i tmp/{} > tmp/{}.sorted'.format(filename,filename))
            os.system('bedtools merge -i tmp/{}.sorted > result/{}.sorted.merged'.format(filename,filename))
            os.system('rm tmp/{}'.format(filename))

fi.close()

combinations输出的结果是一个{}限定起来的组合,不能直接当列表用会报错。

posted @ 2023-03-16 17:37  xjce  阅读(206)  评论(0编辑  收藏  举报