【问题标题】:Simplification of nested for loop嵌套for循环的简化
【发布时间】:2016-10-11 10:58:42
【问题描述】:

此代码有效,但我相信它可以变得更简单,还允许包含额外的部分,而无需在嵌套循环中添加行的所有麻烦。怎么样?

#---------------------------------------------------------------------------        ----
# Name:        TotalweightCombination
# Purpose:      Combine weight/length/etc of pieces to get a sum as close as possible to optSum. Maximally 6 pieces allowed in the resulting combination. 
#-------------------------------------------------------------------------------

pieces=[31.75,12.5,28.9,20.95,31.5,13.8,13.95,11.2,32.9,16.6,8.6,17.85]

print("Sum weight pieces:",sum(pieces))
numpieces=len(pieces)
pieces.append(0)   # We include a piece with weight 0 to allow combinations with fewer than 6 pieces
optSum=142
bestDiff=1000
totCheck=0

for i,iv in enumerate(pieces):
    for j,jv in enumerate(pieces):
        if jv==0 or j!=i:
            for k,kv in enumerate(pieces):
                if kv==0 or k not in [i,j]:
                    for l,lv in enumerate(pieces):
                        if lv==0 or l not in [i,j,k]:
                            for m,mv in enumerate(pieces):
                                if mv==0 or m not in [i,j,k,l]:
                                    for n,nv in enumerate(pieces):
                                        if nv==0 or n not in [i,j,k,l,m]:
                                            totCheck+=1
                                            theList=[iv,jv,kv,lv,mv,nv]
                                            diff=abs(sum(theList)-optSum)
                                            if diff<bestDiff:
                                                bestDiff=diff
                                                chosen=theList
                                                print("New best sum: %s with "%sum(chosen),chosen)

theTotal=sum(chosen)
print("We try to obtain the sum %s with %s pieces. Checked %s combinations. Best combination: %s gives theTotal %s. Deviation %.4f%%."%(optSum,numpieces,totCheck,[i for i in chosen if i!=0],theTotal,100*(theTotal/optSum-1)))

(编辑:更正了一些选项卡错误)

【问题讨论】:

    标签: python for-loop nested-loops simplification


    【解决方案1】:

    您应该使用来自itertools 模块的combinations()

    from itertools import combinations
    
    for theList in combinations(pieces, 6)):
       # theList stands here for exactly the same as in your most inner loop. 
       # Do whatever you want with it here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2012-06-23
      • 1970-01-01
      • 2020-01-14
      • 2015-01-15
      • 2020-08-24
      • 2020-07-06
      相关资源
      最近更新 更多