简体   繁体   中英

I am trying to use filter function with a nested list but I am not able to store the 0'th element of the inner list by using the filter function

I have a nested list as below:

students = [['Jagan', 65.5], ['Kiran', 55.45], ['Maddy', 47.2], ['Harsha', 75.0], ['Pavy', 55.45]]

I am trying to figure out the second lowest scorer for which I am using the function below to find out the second lowest number first,

def second_lowest(l):
small, second_small = float('inf'), float('inf')
for number in l:
    if number[1] <= small:
        small, second_small = number[1], small
    elif number[1] < second_small:
        second_small = number[1]
return second_small

After which I am using a lambda function as below to filter out the name of the second lowest scorer,

sl = second_lowest(students)
names = filter(lambda x: x[0] if (x[1] == sl) else None, students)
print names

I am expecting the output should be only names as I am using x[0] in the equation but I am getting whole list as shown below:

[['Kiran', 55.45], ['Pavy', 55.45]]

The filter() function works a bit different, it should return True or False for each item and only True one will be in the output, so you have to do it in a such way:

names = filter(lambda x: x[1] == sl, students)

to get only names you should use another lambda over it

names = map(labmda x: x[0], filter(lambda x: x[1] == sl, students))

or just one map() instead of filter(), but in that case, you'll get a list fill with None's

names = map(lambda x: x[0] if (x[1] == sl) else None, students)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM