Swan87
Swan87

Reputation: 421

Getting elements by index [Python]

I had this excercise to find the counts of a specific set of persons in a number of given articles without using a dictionary.

I am facing an issue when I am trying to get elements from a list using their index. Specifically imagine that I have 3 lists:

[u'Putin', u'Fattah', u'Vladimir',u'Cameron', u'Bashar', u'al-Baghdadi']
counts : [3, 6, 1, 1, 1, 0]
results: [6, 6, 1, 1, 1, 0]
Sorted results: [6, 6, 1, 1, 1, 0]

First list contains the names of persons, the second their counts, the third one is derived after applying a formula and the fourth one is the third one sorted.

Given that I need to compare the 2 or three higher values and returned the most mentioned person when I do this:

elif res[0] == res[1]:
idx = results[i].index(sorted_res[0])
idx2 = results[i].index(sorted_res[1])
print idx, results[idx]
print idx2, results[idx2]

I get back:

1 Putin
1 Putin

where instead I want to get back:

1 Putin
2 Fattah

Any idea on whether that is possible without using dictionaries?

Thank you in advance.

Upvotes: 0

Views: 479

Answers (1)

Garrett R
Garrett R

Reputation: 2662

I would zip them all together so that you have a list like [('Putin', 3, 6), ('Fattah', 6,6), ...]. Then you can sort by the second element of the tuple (the result).

names = [u'Putin', u'Fattah', u'Vladimir',u'Cameron', u'Bashar', u'al-Baghdadi']
counts = [3, 6, 1, 1, 1, 0]
results = [6, 6, 1, 1, 1, 0]

all_vals = zip(names, counts, results)
in_order = sorted(all_vals, key = lambda x: x[2], reverse = True)
print in_order
print in_order[0][0] #Putin
print in_order[1][0] #Fattah

for i,e in enumerate(in_order):
     print i, e[0]

# 0 Putin
# 1 Fattah
# 2 Vladimir
# ...

Upvotes: 4

Related Questions