-1

I have a list in the following format:

[('car  crash  killed', 95), ('car  accident  crash', 86), ('disaster  police  car', 45)]

I want to extract the string/sentence with the largest number and print it in a text file. In this case, the output will be:

car crash killed

If there two or more strings/sentences with the same largest number, I want to extract all of them.For example:

[('car  crash  killed', 95), ('car  accident  crash', 95), ('disaster  police  car', 45)]

Output:

car crash killed
car accident crash

How to extract?

clawstack
  • 27
  • 3
  • 2
    Can you edit your code to show us what you have tried so far? – Nick Aug 05 '18 at 11:57
  • This is merger of a few questions, the dupe, and https://stackoverflow.com/questions/3989016/how-to-find-all-positions-of-the-maximum-value-in-a-list for example. – kabanus Aug 05 '18 at 11:58

3 Answers3

2

Use max to get item with largest value:

lst = [('car  crash  killed', 95), ('car  accident  crash', 86), ('disaster  police  car', 45)]

print(max(lst, key=lambda x: x[1])[0])
# car  crash  killed

Now, to return all max value items, basically apply the same logic. Get max_value and return all items with the max_value using a list-comprehension like below:

lst = [('car  crash  killed', 95), ('car  accident  crash', 95), ('disaster  police  car', 45)]

max_value = max(lst, key=lambda x: x[1])[1]
print([x[0] for x in lst if x[1] == max_value])

# ['car  crash  killed', 'car  accident  crash']
Austin
  • 25,759
  • 4
  • 25
  • 48
0
from collections import Counter

dictionary = dict([('car  crash  killed', 95), ('car  accident  crash', 95), ('disaster  police  car', 45)])
counter = Counter(dictionary)
max_value = counter.most_common(1)[0][1]
print(max_value)

result = list(string for string, count in counter.most_common() if count == max_value)
print(result)
hyloop
  • 349
  • 1
  • 5
0

Given a list with repeated values (96):

data = [('car  crash  killed', 95),
        ('car  accident  crash', 86),
        ('disaster  police  car', 45),
        ('road', 95)]

Then you sort it by the value and select the highest ones:

data = sorted([(y, x) for x, y in data], reverse=True)
out = []
highest = data[0][0]
for y, x in data:
    if y == highest:
        out.append(x)
print(out)

['road', 'car  crash  killed']

This can be simplified with a list comprehension:

data = sorted([(y, x) for x, y in data], reverse=True)

highest = data[0][0]
out = [x for y,x in data if y==highest]
print(out)

['road', 'car  crash  killed']
joaquin
  • 82,968
  • 29
  • 138
  • 152