Issue
I created a 2D array with n elements!
n = int(input())
a = [[input(),float(input())] for _ in range(n)]
output
a = [['Harry', 37.21], ['Berry', 37.21], ......... ['Akriti', 41.0], ['Harsh', 39.0],['Marsh', 35.5]]
how to find 2nd lowest score & corresponding names using sort() & set() in python,without using multiple loop?
Solution
try this:
a = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.21], ['Akriti', 41.0], ['Harsh', 39.0],['Marsh', 35.5]]
a.sort(key=lambda x: x[1])
print(a)
print('second lowest is :' )
print(a[1])
# these lines add on second edit
import numpy as np
a = np.array(a)
a[[i for i in (range(len(list(a)))) if a[i][1] == a[1][1]],:]
output:
[['Marsh', 35.5], ['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.21], ['Harsh', 39.0], ['Akriti', 41.0]]
second lowest is :
['Harry', 37.21]
array([['Harry', '37.21'],
['Berry', '37.21'],
['Tina', '37.21']], dtype='<U6')
if you want to use set()
you can try this:
a = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.21], ['Akriti', 41.0], ['Harsh', 39.0],['Marsh', 35.5]]
b = set(tuple(t) for t in a)
b = sorted(b, key=lambda x: x[1])
b
output:
[('Marsh', 35.5),
('Berry', 37.21),
('Harry', 37.21),
('Tina', 37.21),
('Harsh', 39.0),
('Akriti', 41.0)]
Answered By - user1740577
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.