当其他列表具有相同的值时,如何获取列表中的True索引?

时间:2019-02-21 09:53:20

标签: python list for-loop match

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厘米

“”“

1 个答案:

答案 0 :(得分:0)

这是解决方案:

A = imread('Yes_Noise.png');
A = imgaussfilt(A, 2); %Filtered image

ref = imread('Yes_Noise.png'); %Noisy image

test = snr(ref,ref-A)

输出:

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']))