473,387 Members | 1,516 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

where or filter on list

Hi,

Can anybody tell me how to to find the nearest value to zero in a list
?

To do that, i'm using list comprenhension :
>>foo = [-5,-1,2,3] # nearest value to zero ?
[value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])]
[-1]

Something simpler ?
How to extend this function to any given value ?

Thanks,

CH.

Aug 30 '06 #1
10 2267
>>>foo = [-5,-1,2,3] # nearest value to zero ?
>>>[value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])]
charles[-1]

charlesSomething simpler ?

Well, you can just use the abs() builtin instead of math.fabs. Also, just
compute the min/abs once:

minval = min([int(math.fabs(x)) for x in foo])
[value for value in foo if fabs(value) == minval]

Another way might be to sort by absolute value:

intermed = [(abs(v), v) for v in foo]
intermed.sort()
intermed[0][1]

That only gives you one of possibly many values closest to zero.

charlesHow to extend this function to any given value ?

Just subtract that value from all values in the list:

intermed = [(abs(v-x), v) for v in foo]
intermed.sort()
intermed[0][1]

Skip
Aug 30 '06 #2
sk**@pobox.com wrote:
Another way might be to sort by absolute value:

intermed = [(abs(v), v) for v in foo]
intermed.sort()
intermed[0][1]
It is slightly simpler if you use sorted (assuming a recent enough Python):

intermed = sorted(foo, key=abs)
print intermed[0]

The sorted list is of course the best way if you want to find not just one
value but a group, e.g. the n nearest to 0.

For nearest to a non-zero value v the version with sorted becomes:

intermed = sorted(foo, key=lambda x:abs(x-v))
Aug 30 '06 #3
ch************@gmail.com <ch************@gmail.comwrote:
Can anybody tell me how to to find the nearest value to zero in a
list?
>foo = [-5,-1,2,3] # nearest value to zero ?
[value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])]
[-1]
Something simpler ?
Maybe something like this:

mindist = min(map(abs, foo))
filter(lambda x: abs(x) == mindist, a)[0]

Only annoyance: we compute abs twice for each value. We could probably
avoid that by using reduce() and a suitable function...
How to extend this function to any given value ?
By subtracting the desired value from foo.

cu
Philipp

--
Dr. Philipp Pagel Tel. +49-8161-71 2131
Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186
Technical University of Munich
http://mips.gsf.de/staff/pagel
Aug 30 '06 #4
ch************@gmail.com wrote:
Hi,

Can anybody tell me how to to find the nearest value to zero in a list
?

To do that, i'm using list comprenhension :
>>>foo = [-5,-1,2,3] # nearest value to zero ?
[value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])]
[-1]

Something simpler ?
How to extend this function to any given value ?

Thanks,

CH.
One of I'm sure many ways:

import sys
def closest(value, list):
m=None
mdistance=sys.maxint
for entry in list:
distance=abs(value-entry)
if distance < mdistance:
m=entry
mdistance=distance
return m

if __name__ == "__main__":
foo = [-5,-1,2,3]
print closest(0, foo)

Note: If you know that the list is ordered you can break out of the
loop you can optimize the loop by breaking out when you start getting
further away from value or you might be able to use the bisect module
to find it faster. If the lists are small it probably isn't worth
the extra effort. If they are large and sorted look at bisect.

Question: what if two values are equidistant?

-Larry bATES
Aug 30 '06 #5
Thanks all !
Question: what if two values are equidistant?
>>def closest(foo,v):
.... intermed = [(abs(v), v) for v in foo]
.... intermed.sort()
.... return [x[1] for x in intermed if x[0] == intermed[0][0]]
....
>>print closest([-20,-10,10,15],0)
[-10, 10]

Works fine !

(now with sorted ... ?)

Aug 30 '06 #6
>Another way might be to sort by absolute value:

intermed = [(abs(v), v) for v in foo]
intermed.sort()
intermed[0][1]
DuncanIt is slightly simpler if you use sorted (assuming a recent
Duncanenough Python):

Duncan intermed = sorted(foo, key=abs)
Duncan print intermed[0]

Yeah, sorted() is new enough that my brain generally doesn't realize it's
available. I also never remember the key parameter to list.sort(). Now
that you mention it:
>>foo = [5, 2, -1, -7, 3, -6, 2, 12]
foo.sort(key=abs)
foo
[-1, 2, 2, 3, 5, -6, -7, 12]

(assuming you don't mind reording the list - if you do, then sorted() is
your friend).

Skip
Aug 30 '06 #7
On 2006-08-30, ch************@gmail.com <ch************@gmail.comwrote:
Hi,

Can anybody tell me how to to find the nearest value to zero in a list
?

To do that, i'm using list comprenhension :
>>>foo = [-5,-1,2,3] # nearest value to zero ?
[value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])]
[-1]

Something simpler ?
How to extend this function to any given value ?
A hand-crafted loop seems like an efficient solution:

def closest_to(n, seq):
m = 0
for i in xrange(1, len(seq)):
if abs(n-seq[i]) < abs(n-seq[m]):
m = i
return seq[m]

Putting my faith in Python builtins instead:

def closest_to(n, seq):
s = [abs(n-x) for x in seq]
return seq[s.index(min(s))]

--
Neil Cerutti
Aug 30 '06 #8
sk**@pobox.com wrote:
>
>Another way might be to sort by absolute value:
>>
>intermed = [(abs(v), v) for v in foo]
>intermed.sort()
>intermed[0][1]

DuncanIt is slightly simpler if you use sorted (assuming a recent
Duncanenough Python):

Duncan intermed = sorted(foo, key=abs)
Duncan print intermed[0]

Yeah, sorted() is new enough that my brain generally doesn't realize it's
available. I also never remember the key parameter to list.sort().
You're not the only one who has trouble remembering just what is in each
version.
Now that you mention it:
>>foo = [5, 2, -1, -7, 3, -6, 2, 12]
>>foo.sort(key=abs)
>>foo
[-1, 2, 2, 3, 5, -6, -7, 12]

(assuming you don't mind reording the list - if you do, then sorted() is
your friend).
And for Python 2.5 users only we have the exciting new option of:
>>foo = [5, 2, -1, -7, 3, -6, 2, 12]
min(foo, key=abs)
-1

Aug 30 '06 #9
Duncan Booth:
And for Python 2.5 users only we have the exciting new option of:
>foo = [5, 2, -1, -7, 3, -6, 2, 12]
min(foo, key=abs)
-1
Good. This is possibility for older Python:

l = [(rnd()-0.5) * 20 for i in xrange(1000)]
print min( (abs(el), el) for el in l )[1]

Bye,
bearophile

Aug 30 '06 #10
What I mean is: What if there are two items that are
equidistant to what you are searching for?
Example:

foo = [-5,-1,1,3,5]
print closest(0, foo)

-1 and 1 are both "equally close" to zero that I'm
searching for. This is an edge case that you didn't
define an answer to and closest function that I
wrote may (or may not) return the correct answer.

-Larry

ch************@gmail.com wrote:
Thanks all !
>Question: what if two values are equidistant?
>>>def closest(foo,v):
... intermed = [(abs(v), v) for v in foo]
... intermed.sort()
... return [x[1] for x in intermed if x[0] == intermed[0][0]]
...
>>>print closest([-20,-10,10,15],0)
[-10, 10]

Works fine !

(now with sorted ... ?)
Sep 1 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Salad | last post by:
I have a log file with a list of records. The log file can be unfiltered or filtered. I have a command button to call a data entry form from the log. At first I was only going to present the...
8
by: John Welch | last post by:
I have a command button with the following code: DoCmd.OpenForm "frmSearchAssignments", , , "SearchAssignmentID = 1" (SearchAssignmentID is the PK, auto number) When it runs, the form opens but...
3
by: Vern | last post by:
The following code retrieves data into a dataset, and then creates a dataview with a filter. This dataview is then attached to a combobox. When the effective date changes, I would like to see the...
1
by: Peter Alberer | last post by:
Hi there, i have a problem with a query that uses the result of a plsql function In the where clause: SELECT assignments.assignment_id, assignments.package_id AS package_id,...
8
by: marcus.kwok | last post by:
I am having a weird problem and I have can't figure out why it is happening. I create an OpenFileDialog and set a filename filter. When the dialog first opens, the filter works correctly, and...
3
by: rreitsma | last post by:
I want to create a form that will allow the user to select from a list of available reports and based on a filter limit the records displayed in the report. I have figured out how to access the...
4
by: Cron | last post by:
Hi can someone give me a hand with this please? I'm trying to build a search filter that scans through a list of client names in a database as you type into a text box and filters the form records...
2
by: Ceebaby via AccessMonster.com | last post by:
Hi Folks I wondered if someone could point me in the right direction before I completely tear my hair out. I have a user selection form where options can be selected for a report. Users now...
3
by: Soulspike | last post by:
Form name to filter = frmSortFor Filter based on list box from frmTest= lstSortFor Form containing list box = frmTest Field (CompCodes) data format = "PM SM TS EW WA" I have a database that I...
4
by: =?Utf-8?B?TWlrZSBDb2xsaW5z?= | last post by:
I am trying to set up a dynamic search using linq. I believe the syntax is correct, but cannot confirm it because when I try to cast my Session from a List<to IQueryable<>, I get a cast error...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.