0

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.

3
  • third one is derived after applying a formula - It is not clear what that formula is Commented Feb 10, 2016 at 0:17
  • How are you getting the counts and why no dictionary? Commented Feb 10, 2016 at 0:24
  • @PadraicCunningham It's a prerequisite. I am using NLTK's posTagger and collections library to get the counts of all words and then I extract the ones I care about Commented Feb 10, 2016 at 1:02

1 Answer 1

4

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
# ...
Sign up to request clarification or add additional context in comments.

2 Comments

Not at all. It's good way to show how the answer generalizes beyond just the top 2.
That is exactly what I needed! Cheers mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.