当其他列表具有相同的值时,如何在列表中获得真正的索引?

2024-04-25 10:13:41 发布

您现在位置:Python中文网/ 问答频道 /正文

heights=[67, 67, 55, 65, 55, 61, 61, 58, 40, 65]
box_numbers=[1,2,3,4,5,6,7,8,9,10]

"""
Tallness of 1 numbered box  is 67 cm.   
Tallness of 10 numbered box  is 65 cm.  
"""
heights=sorted(heights,reverse=True) # I sorted list max to min cm [67>> 67>> 65>> 65>> 61>> 61>> 58>> 55>> 55>> 40]

group_heights=[] 
group_box_numbers=[]  

while heights:
 for h in heights:
  if sum(group_heights)+h<=120: # I wrote this code to find max numbers whice are less than 120 cm. 
                                      # It will sum numbers until close to 120 cm
   group_heights.append(h)     # Heights which are the most close to 120 cm will be added to empty list
   group_box_numbers.append(box_numbers[heights.index(h)]) #PROBLEM!!!: THERE ARE SAME NUMBERS IN HEIGHTS SO WHEN I SAID FIND H IN HEIGHTS IT'S CONFUSING.
   box_numbers.remove(box_numbers[heights.index(h)]) 
   heights.remove(h)           # I can use each number in heights list only one time.

 for height,box_number in zip(group_heights,group_box_numbers): # This loop is helping me which heights are putted empty list and gathered.    
  print(height,box_number)
 print("Total ",sum(group_heights)," cm") 
 group_heights.clear()  #group_heights each time is cleared until loop is done for to show which numbers gathered.
 group_box_numbers.clear()
 print("")

“”“

我的输出:

第67页共1页

40至10

总计107厘米

第67页共2页

总共67厘米

65年3月

55 8个

总共120厘米

65年4月

55.9条

总共120厘米

61.5条

58.7条

总计119厘米

61.6条

总计61厘米

我的预期结果:

第67页共1页

40 9岁

总计107厘米

第67页共2页

总共67厘米

65年4月

55.3条

总共120厘米

65年10月

55年5月

总共120厘米

61.6条

58 8个

总计119厘米

61.7条

总计61厘米

“”“


Tags: toinboxnumberwhichforisgroup
1条回答
网友
1楼 · 发布于 2024-04-25 10:13:41

以下是解决方案:

heights = [67, 67, 55, 65, 55, 61, 61, 58, 40, 65]
box_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def find_pairs(val):
    i = 0
    while i < len(data):
        val1 = data[i]['height']
        val2 = val-val1
        el2 = [x for x in data if val2 == x['height'] and x != data[i]]
        if el2:
            print(val1, data[i]['box'])
            print(val2, el2[0]['box'])
            data.remove(data[i])
            data.remove(el2[0])
            print('Total {} cm\n'.format(val1 + val2))
        i += 1

data = []
for h, b in zip(heights, box_numbers):
    data.append({'height': h, 'box': b})

for desired_sum in range(120, 0, -1):
    find_pairs(desired_sum)

for d in data:
    print(d['height'], d['box'])
    print('Total {} cm\n'.format(d['height']))

输出:

55 3
65 4
Total 120 cm

65 10
55 5
Total 120 cm

61 6
58 8
Total 119 cm

67 1
40 9
Total 107 cm

67 2
Total 67 cm

61 7
Total 61 cm

相关问题 更多 >