3

I have a list that I am trying to compare to a sequential combination of values in two other lists. The code below works, but the output values are in a single, flat list.

values = [3,6,7,8]
list1 = [2,5]
list2 = [4,8]
main = []

for i in values:
    for x,y in zip(list1, topElevation):
        if x<i<y:
            main.append(i)
>>>[3,6,7]

How can I organize the script so that it splits the values into multiple lists such that the first nested list takes all the values of list1[0]<i<list2[0], the second list1[1]<i<list2[1], and so on... (through list1[n]<i<list2[n])? In that case, the output would be:

>>>[[3],[6,7]]

3 Answers 3

5

You could use a List Comprehension with a filter to do this:

>>> [filter(lambda x: l < x < r, values) for l, r in zip(list1, list2)]
[[3], [6, 7]]

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

So equivalent solution:

>>> [[item for item in values if l < item < r] for l, r in zip(list1, list2)]
[[3], [6, 7]]

Details:

filter(function, iterable)

Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator.

3
  • 1
    it's too much for a beginner, i added list comprehension version to my answer without filter/lambda
    – midori
    Jan 26, 2016 at 5:12
  • 1
    I thought I've given enough docs on those. BTW, I don't think it's too much to learn.
    – luoluo
    Jan 26, 2016 at 5:20
  • that's why you copied my solution :)
    – midori
    Jan 26, 2016 at 5:21
4

You need to create empty list and put number into this list before you append it to main. And you have to use for loops in different order.

values = [3,6,7,8]
list1 = [2,5]
list2 = [4,8]
main = []


for x, y in zip(list1, list2):
    temp = []
    for i in values:
        if x<i<y:
            temp.append(i)
    main.append(temp)

print(main)
2
  • I saw you answer after I press Save
    – furas
    Jan 26, 2016 at 5:00
  • @minitoto lambda and filter are nice but hard to explain to beginner :)
    – furas
    Jan 26, 2016 at 5:04
2

Read about List Comprehension. You can use it here:

values = [3,6,7,8]
list1 = [2,5]
list2 = [4,8]

print [[i for i in values if x<i<y] for x,y in zip(list1, list2)]

Or changing your code a little bit:

main = []

for x,y in zip(list1, list2):
    mid = []
    for i in values:
        if x<i<y:
            mid.append(i)
    main.append(mid)

print main

Output in both cases:

[[3], [6, 7]]
1
  • Helpful to have the list comprehension next to the full version for comparison's sake. Thanks!
    – stdmn
    Jan 26, 2016 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.