Python Forum

Full Version: get positive number from a list if there's the same number but negative
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
list_one = [-8, 8, 144, 17]

def test(lis):
    return min(lis, key=abs)

print test(list_one)
Output:
-8
i want to print the closest number to 0 from a list,
in this case, -8 and 8 are the two closest number to 0, but i get the first number of the list(-8), and i would like that if there is two numbers which are as close each other to 0 (so like in this case, -8 and 8) I'd like to get the positive number ( so 8 )
how could i do that , thanks

well, resolved doing this,

list_one = [-8, 8, 144, 17]
 
def test(lis):
    m = min(lis, key=abs)
    if m < 0:
        if m and m*-1 in lis:
            return m*-1
        else:
            return m
    else:
        return m

print test(list_one)
new output :
Output:
8
was there a simpler way ?
Yes

list_one = [-8, 8, 144, 17]
min(filter(lambda x: x >= 0, list_one))
i will look at it , thanks
With the list = [-8, 144, 17]
I get -8 with first programm
and 17 with second program.
hi heiner, this is weird, it's not the case for me,
with first program, i get -8
with second program, -8 too
Take my list = [-8, 144, 17], not the original one.
this is what i did :

list_one = [-8, 144, 17]
 
def test(lis):
    return min(lis, key=abs)
 
print test(list_one)
Output:
-8
----

list_one = [-8, 8, 144, 17]
  
def test(lis):
    m = min(lis, key=abs)
    if m < 0:
        if m and m*-1 in lis:
            return m*-1
        else:
            return m
    else:
        return m
 
print test(list_one)
Output:
-8
Sorry, with second program, I meant this:

list_one = [-8, 144, 17]
print(min(filter(lambda x: x >= 0, list_one)))
oh yes, you're right, it seems to work only for positives numbers, i finally used this way:


list_one = [-8, 8, 144, 17]
def test(lis):
    m = min(lis, key=abs)
    if m and -m in lis:
        return abs(m)
    else:
        return m

print test(list_one)
Output:
8
and with you're list:

list_one = [-8,  144, 17]
def test(lis):
    m = min(lis, key=abs)
    if m and -m in lis:
        return abs(m)
    else:
        return m

print test(list_one)
Output:
-8
Why
    if m and -m in lis:
and not only:
    if -m in lis:
?

I think "if m" is always true (except 0).
Or did you mean:
if m in list and -m in list:
Pages: 1 2