da1g
da1g

Reputation: 117

Connecting 2 elements in a list

I have a function that takes an argument 'i' and returns 'a'.

'a' is placed in a list with list.append(a) and 'i' changes value (i is in a for-loop).

I later want to sort the list from largest to smallest, and be able to print out this sorted list, and for every 'a' printed, I want the corresponding 'i' aswell.

I thought about putting 'i' in a list aswell and "copying" the sorting order of the 'a'-list. But have no idea is this is a good way, or if it can even be done.

How do I sort the list containing values of 'a' and keep each 'a' connected to it's unique 'i'? So if I want to find which value of 'i' gave the 3rd largest 'a', I can do so. edit: code looks like this (kind of)

for i in range(1, 100):
    a = function(i)
    list.append(a)
list.sort   #highest value of a first
print("Highest value of a was" + list[0] + "given by i:" + <i that produced list[0]>

Upvotes: 1

Views: 691

Answers (2)

Odysseas
Odysseas

Reputation: 1060

You can use a list comprehension to keep the result and the input associated in a tuple.

# Apply the function to desired number range using a list comprehension
results = [(function(i), i) for i in range(1, 100)]
# Sort by the first element of each tuple, from largest to smallest
results = sorted(results, key=lambda t: t[0], reverse=True)
# Use a string formatting operation to display result
print("Highest value of a was {0} given by i: {1}".format(results[0][0],  results[0][1]))

Upvotes: 1

Pablo
Pablo

Reputation: 642

You can create a class to put your list items in and pass a key to the sort function so it knows how to sort your list:

class ListItem():

  def __init__(self, value, index):
    self.value = value
    self.index = index


item1 = ListItem('test1', 1)
item2 = ListItem('test2', 2)
item3 = ListItem('test3', 3)

unsortedList = [item2, item3, item1]
unsortedList.sort(key = lambda item: item.index)

for item in unsortedList:
  print('index: ' + str(item.value) + ', value: ' + str(item.index))

Output:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

index: test1, value: 1
index: test2, value: 2
index: test3, value: 3

Upvotes: 1

Related Questions