[Tutor] Selecting from list
Jim Mooney
cybervigilante at gmail.com
Sat Jul 20 00:21:10 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.
Looks like my last message didn't get delivered, so I'll post this as
a late response:
Here's the whole thing in a list comprehension, which as mentioned, is still an
unseen loop, but which is faster than one written out. Although as also
mentioned, numpy is even faster for a huge amount of data. Although I
think that
means huge lists, not necessarily a huge record base, since accessing records
would dwarf any style of processing a short list. Since I'm not sure
what was required, I took the 'greedy' option of listing all 3-tuples
that fulfilled
the requirement as I understood it. The comprehension also takes care
of eliminating
endpoints that would cause an index-error crash. I changed the data to
add a bunch
of possible gotchas ;')
a = [0,3389, 178, 2674, 199, 2586, 13731, 12, 13, 14, 3189, 15, 785, 10, 1038,
25956, 6, 8, 2, 3551, 2]
meets_requirements = [(a[idx-1],a[idx],a[idx+1]) for idx in range(1,len(a)-1) \
if a[idx] < 200 and a[idx-1] > 1000 and a[idx+1] > 1000]
# result [(3389, 178, 2674), (2674, 199, 2586)]
--
Jim
The universe is made up of patches that are only woven together as
they are accessed. Sometimes a stitch is dropped and something really
weird happens. Only nobody will ever believe you
More information about the Tutor
mailing list