[SOLVED] List Returns firts Item of Duplicates Work Around Python


This Content is from Stack Overflow. Question asked by Anasse Gs

Good[ Morning : Evening ]

Im trying to make a small programme that :

-reads a text file containing numbers -assigned each line into an element of int_list

-takes a given list (max_quantity) and divides all the elements by 2 resulting in (max_q_in_half)

  • takes (int_list) and compares each element to its counterpart in (max_q_in_half) to eliminate each element that is above 50% of its maximum value (max_quantity)

-then make all the elements that are below 50% of their maximum value
into a new list (new_list)

-then return the smallest number in the (new_list)

-then uses that number to get it’s index in the original (int_list)

-then uses that index to match the number to it’s element in (metal_list)

  • to return the metal that is about to run out from the stock so the it could be restocked


As you see in the output of this code the numbers below 50% are [41, 1]
the lowest value is 1 which has the index 6

but when i search int_list for this value it returns the firt occurence of 1 which is at index 3 which coresponds to BRASS but the correct answer should be Titanium

im triying to work around this issue by assigning a weight to each line in the text file so when i search the index of a value that value would be unique
take into account that the lines vary in number in the original text file

could somebody help me make a programe that assignes wheights of X.01 to line one and X.02 to line two …

-41.01 #Line_1

-20.02 #Line_2

-6.03 #Line_3

-1.04 #Line_4

-14.05 #Line_5

-6.06 #Line_6

-1.07 #Line_7

int_list = [41, 20, 6, 1, 14, 6, 1]

metal_list = ['aluminium', 'iron', 'zinc', 'brass', 'stainless steel','copper', 'titanium']

max_quantity = [ 100, 30, 6, 2, 18, 7, 15]

max_q_in_half = [x // 2 for x in max_quantity]

new_list = [i for i, j in zip(int_list, max_q_in_half) if i < j]

x = min(new_list)

v = int_list.index(x)
w = metal_list.__getitem__(v)

print("Current List ", int_list)

print("what is below 50%",new_list)
print('lowest value ',x)

print("position in int_list  ",v)

print("position Metal_list ",w)


You can divide the elements of the list by 2 when checking. It is better to number it when creating a list, but with the second member, so that the number does not interfere when checking for a minimum.

int_list = [41, 20, 6, 1, 14, 6, 1]
metal_list = ['aluminium', 'iron', 'zinc', 'brass', 'stainless steel', 'copper', 'titanium']
max_quantity = [100, 30, 6, 2, 18, 7, 15]

x = min([(i, n) for n, (i, j) in enumerate(zip(int_list, max_quantity)) if i < j//2])
w = metal_list[x[1]]
print("position Metal_list ", w)

(1, 6)
position Metal_list  titanium

This Question was asked in StackOverflow by Gibbs and Answered by Сергей Кох It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?