[Tutor] Selecting from list

Jim Mooney cybervigilante at gmail.com
Fri Jul 19 02:18:14 CEST 2013


On 18 July 2013 10:27, Hs Hs <ilhs_hs at yahoo.com> wrote:
> hi list:
>
> In the following list, is there a simply way to find element less than 200
> sandwiched between two numbers greater than 1000.
>
> a = [3389, 178, 2674, 2586, 13731, 3189, 785, 1038, 25956, 33551]
>
> in a, 178 is between 3389 and 2674.  How this particular list can be
> selected for further processing.
> (sorry this is not homework question. I want to avoid looping, because I
> have 300K lines to parse through)
>
> Thanks
> Hs.

Not sure what you want to do. If you only want to fulfill the test once,
here is a way without a loop, using a list comprehension.

#Using Python 2.7 on win 7
from __future__ import print_function

a = [3389, 3666, 13, 2586, 13731, 2, 785, 1038, 25956, 33551, 199, 1500]
under_200 = [x for x in xrange(0,len(a)) if a[x] - 200 < 0]

#result: [2, 5, 10] - the indexes of list a for items < 200

# At this point I'm not sure what you want to do - if the triplet of over-1000
# sandwiching under-200 occurs more than once matters to you or not to you.

# Either way you have a list of indexes of anything under 200.

# If you're only interested in one triplet fulfilling,  you're done:
# a[index-1] > 1000 and a[index+1] > 1000 says the list passes the
test and you can gather
# the numbers into a 3-tuple using the indexes if you want to print them out.

# If you have to test more than once, you should probably loop through
the under_200 list. And of # course,  you have to test for invalid
index when you add or subtract to check for numbers over
# 1000. Actually, you could probably replace the second loop with a
comprehension, but
# I think that's getting too complicated.

>Jim


More information about the Tutor mailing list