Johnathan Scott
Johnathan Scott

Reputation: 291

How to search using input to find certain values in a sorted, nested list?

So right now I have a nested list that I've sorted using a bubble sort. The code looks something like this:

def bubbleTop5(bad_list):
    length = len(bad_list) - 1
    sorted = False
    while not sorted:
        sorted = True
        for i in range(length):
            if bad_list[i][1] <= bad_list[i+1][1]:
                sorted = False
                bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]

This sorts the lists based on their [1]th element and prints out a list similar to this:

[['California', 4964, 76, 22], ['Texas', 3979, 62, 23], ['New York', 1858, 69, 20], ['Virginia', 1655, 60, 19], ['Maryland', 1629, 66, 20]]

Now, what I'm trying to do is make the user input a number for the [3]th element in these lists and only show those states with that value. So if I were to input 7, then it would only show states with a value of 7 or higher in the [3]th element. Any help is appreciated :)

Upvotes: 0

Views: 220

Answers (3)

Christian Tapia
Christian Tapia

Reputation: 34146

You can use raw_input to get the input and a list comprehension to get the result:

key = int(raw_input("Enter a number: "))
result = [e for e in bad_list if e[3] >= key]

Note that raw_input will return a string, so you should convert it to an integer using int(...).

Upvotes: 1

sundar nataraj
sundar nataraj

Reputation: 8692

you can sort the list

 badlist=sorted(bad_list,key=lambda x :x[1])  

n = int(raw_input("Enter search value: ")) take the input and you can use filter the elements which has greater than input element

result = filter(lambda x : x[3] >=n,sorted_list)

Upvotes: 1

holdenweb
holdenweb

Reputation: 37003

Try this:

n = int(raw_input("Enter search value: "))
result = [x for x in sorted_list if x[3] >= n]

Also note that your sort could be achieved with

sorted_list.sort(key=lambda x: x[1])

For a large list this will generally be MUCH faster than a bubble sort written in Python.

Upvotes: 1

Related Questions