gpt4 book ai didi

python - 嵌套for循环的简化

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:31 25 4
gpt4 key购买 nike

这段代码可以工作,但我相信它可以变得更简单,还允许包含额外的部分,而无需向嵌套循环添加行的所有麻烦。怎么办?

#---------------------------------------------------------------------------        ----
# 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)))

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

最佳答案

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

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

关于python - 嵌套for循环的简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com