mglmnc
mglmnc

Reputation: 1460

Splitting a list in python

Hey im new to python. How do you get a portion of a list by the relative value of its sorting key.

example...

list = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10]
list.sort()
newList = list.split("all numbers that are over 13")
assert newList == [14,15,16]

Upvotes: 2

Views: 202

Answers (2)

YOU
YOU

Reputation: 123917

>>> l = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10]
>>> sorted(x for x in l if x > 13)
[14, 15, 16]

or with filter (would be a little bit slower if you have big list, because of lambda)

>>> sorted(filter(lambda x: x > 13, l))
[14, 15, 16]

Upvotes: 3

Mike Graham
Mike Graham

Reputation: 76783

Use [item for item in newList if item > 13].

There is a decent chance this could be replaced with the generator expression (item for item in newList if item > 13), which filters lazily rather than storing the whole list in memory.


You might also be interested in changing the code just a bit to something like

all_numbers = [11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_sorted_numbers = sorted(number for number in all_numbers if number > 13)

which performs the sorting—a worst case O(n log n) operation—on only the filtered values.

Upvotes: 3

Related Questions