kate88
kate88

Reputation: 371

Extracting information from lists

I have two lists I would like to compare and create another list as a result

list1 = [0.5, 1]
list2 = [0.0, 0.4, 0.5, 0.6. 0.75, 0.99, 1]

I would like to create a third list, containing all the numbers from list2 between 2 elements in list1

list3 = [0.5, 0.6, 0.75, 0.99, 1]

I tried:

 for i in range(list1[0], list1[1], step):
    print i

but my step is not the same in each case, so it does not work, what else could I try?

Cheers!

Upvotes: 2

Views: 93

Answers (2)

steveha
steveha

Reputation: 76715

list1 = [0.5, 1]
list2 = [0.0, 0.4, 0.5, 0.6, 0.75, 0.99, 1]

low, high = list1
lst = [x for x in list2 if low <= x <= high]
print(lst)

Just for readability, we unpack the first list into two variables, low and high.

We use a list comprehension to get values from list2. The list comprehension has a "filter" expression to select just the values we want.

It is better to directly iterate over the values of the list, than to try to use range() to get indices into the list. The code is easier to write, easier to read, and as a bonus it's faster.

The list comprehension solution is the recommended way to solve this problem in Python.

Matthew Graves suggested that "you might be able to do a lamba/map function here". I'll explain how to do that.

filter() needs you to pass in a function; you can define a function, or use the lambda keyword to make an anonymous function. A lambda must be a single expression, but luckily in this case that's all we need.

low, high = list1
def check_low_high(x):
    return low <= x <= high

lst = list(filter(check_low_high, list2))

lst = list(filter(lambda x: low <= x <= high, list2))

In Python 2.x you don't really need to call list() because filter() returns a list. In Python 3.x, filter() is "lazy" and returns an iterator.

Upvotes: 1

SethMMorton
SethMMorton

Reputation: 48735

range only returns integers. You probably want something like this:

for i in list2:
    if i > list1[0] and i < list1[1]:
        print i

You may want to change > to >= and < to <= if needed.

If you want to construct list3 directly try:

list3 = [i for i in list2 if i > list1[0] and i < list1[1]]

Edit

For good measure, you can also do (which is how you would write it mathematically):

list3 = [i for i in list2 if list1[0] < i < list1[1]]

Upvotes: 4

Related Questions