user3457749
user3457749

Reputation: 1043

How do I sort a list under a condition in python?

Assume there is a list [1,9,7,3,6]. I want to produce a new list which is sorted and smaller than one of the integers, for example the integer is 7, so the new list should be list:

[1,3,6]

Upvotes: 3

Views: 1590

Answers (7)

user3804919
user3804919

Reputation:

You can use list comprehension as follow

mylist = [11, 16, 9, 6, 3, 15, 1, 18, 7, 10, 13, 5, 12, 2, 0, 4, 19, 14, 17, 8]
[x for x in sorted(mylist) if x<7]

Result:

[0, 1, 2, 3, 4, 5, 6]

Hope that helps

Upvotes: 1

user2963623
user2963623

Reputation: 2295

Try this:

num = #some number
new_list = sorted(old_list)[:sorted(old_list).index(num)]

OR Alternative

num = 7
somelist = [3,6,7,1,2,8,9,4,5,12]
somelist.sort()
somelist[:somelist.index(num)]

OUTPUT:
[0, 1, 2, 3, 4, 5, 6]

Upvotes: 3

pillmuncher
pillmuncher

Reputation: 10162

Lists have a sort method:

old_list = [1,9,7,3,6]
new_list = [x for x in old_list if x < 7]
new_list.sort()

Upvotes: 4

B.M. Turbo
B.M. Turbo

Reputation: 31

You can use a list comprehension:

sorted([i for i in [1,9,7,3,6] if i < 7])

You can also use a generator:

sorted(i for i in [1,9,7,3,6] if i < 7)

Note: The list comprehension version executes ~2x faster.

Upvotes: 3

Adeel
Adeel

Reputation: 781

aa = filter(lambda x: x < 7, [1,9,7,3,6])
aa.sort()
print aa

OUTPUT:
[1, 3, 6]

Upvotes: 1

Qlaus
Qlaus

Reputation: 915

You can use list-comprehension to do that:

my_list = [1,9,7,3,6]
result = sorted([x for x in my_list if x < 7])

Upvotes: 5

Derek Redfern
Derek Redfern

Reputation: 1009

oldList = [1,9,7,3,6]
myInt = 7
newList = sorted([x for x in oldList if x < myInt])

This is a Python "list comprehension" - it looks at each element in oldList and adds it to newList if and only if it's smaller than the integer you've chosen. Additionally, the sorted() method is native in Python.

Here's a good resource for list comprehensions for the future: http://www.pythonforbeginners.com/basics/list-comprehensions-in-python

Hope that helps!

Upvotes: 4

Related Questions