I have two different lists (same size), say a and b. Both of them contain objects, and every object has the same attribute "Cost" (with different values, of course). I want to build a new list c, which containts randomly selected objects from a, e.g. by using random.choice() and then checking which of these objects in c has the highest value concerning it's attribute "Cost". But i also want to build a new list d, which containts a selection of the objects of b, which should NOT be selected randomly but with the same index of the one with the highest value from list c. And thats my problem.
I tried building a new list, say a1, with enumerate, so this list contains tuples with two elements: First the "index" and second the object. Then i generated the new list c by randomly selecting tuples from a1. I was also able to figure out which of these objects of c has the highest attribute using max(). But the output is just the object, and not the complete tuple including the "index". So since i don't know which index this object had, i can't choose the corresponding object of list b.
Here is an example:
a = [[1,2],[3,4],[5,6]]
Note: All three objects ([1,2] and [3,4] and [5,6]) have one attribute "Cost", which in this case is "10", "100" and "1000", respectively.
a1 = list(enumerate(x))
c = [random.choice(a1) for i in range(2)]
Now i want fo figure out which of the two objects in c has the highest value concerning the attribute "Cost". So i try this:
max([x[1] for x in c], key=attrgetter("Cost"))
This works, but i only get the object which has the highest value, in this case it's [5,6], and not the corresponding "index" (so the first item of the tuple), which in this case would be 2 (or 3, depending on where the enumerate() starts).
I found something like this:
max(c, key=itemgetter(1))[0]
But there it only checks the second item of the tuple (object), and not the value of the attribute corresponding to this object.
Any chance for solving this problem?
Aucun commentaire:
Enregistrer un commentaire