简体   繁体   中英

Trying to sort a list by values closest to zero, using absolute value in python

I've spent quite some time searching to see if there was a similar issue. Unfortunately, I couldn't just comment on the previously asked question to see why my attempt was not working. On this site there exists a question where a person wants to sort a list, according to closest numbers to a specific value. his example: not verbatim copying his example but putting a working solution

list_x = [1,2,5,11]
list_x.sort(key = lambda x: abs(x-4))

which will return the list sorted by values closest to 4 (5,2,1,11) However, when trying to sort a much larger list by values closest to zero this is happening to me:

listA.sort(key = lambda x: abs(x))

Traceback (most recent call last):
  File "<pyshell#382>", line 1, in <module>
    listA.sort(key = lambda x: abs(x))
  File "<pyshell#382>", line 1, in <lambda>
    listA.sort(key = lambda x: abs(x))
TypeError: bad operand type for abs(): 'str'

What exactly am I doing incorrectly thats preventing the list from being sorted by absolute values?

This is input data for what makes listA

for i in decrange(0, 13, i):
   code = (func(seq, float(i)))
   codes = '%.3f' % code
   listA.append(float(codes))
   listB.append(str(codes))
listA.sort(key = lambda k: abs(k))
x = listA[0]
answer = listB.index(x) * float(.01)

The error you're getting seems fairly self-explanatory:

TypeError: bad operand type for abs(): 'str'

It looks like somewhere in your list you have a string value instead of a numeric value. This will work (assuming integer values):

listA.sort(key = lambda x: abs(int(x)))

...but it would be better to figure out why your list has strings in it and fix that instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM