How to change variable from list to float

Peter Pearson pkpearson at nowhere.invalid
Mon Jun 5 13:15:26 EDT 2017


On Mon, 5 Jun 2017 11:13:54 +0100, Paul Barry wrote:
> On 3 June 2017 at 15:42, Gary Barker <barkerg at davincibb.net> wrote:
>
>> I have searched for a solution to this but have not found a suitable
>> example.
>>
>> The attached code generates this error: Traceback (most recent call last):
>>   File "calcsignal.py", line 7, in <module>
>>     siglevfromexist = 34.8 + existattn
>> TypeError: unsupported operand type(s) for +: 'float' and 'list'
>>
>> How do I convert the list variable (i.e. existattn) to a float?
>>
>> Operating details are:
>> Python 3.4.2
>> Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux
>>
>> The following lines are the code in calcsignal.py:
>> azdegpattrev = -47.40715077970316
>> azattndic = {-0.9: [-0.55], -0.5: [-0.46], 3.5: [-21.0], 1.4: [-7.48],
>> 5.5: [-25.0], 0.0: [0.0], 1.9: [-21.0], 13.0: [-38.0], 15.0: [-39.0], 3.6:
>> [-25.0], 20.0: [-39.0], -1.4: [-7.48], 90.0: [-65.0], -0.4: [-0.39], 0.5:
>> [-0.46], 0.1: [-0.04], 1.0: [-1.31], -90.0: [-65.0], 40.0: [-42.0], 180.0:
>> [-65.0], 1.5: [-10.0], -1.2: [-3.69], 0.3: [-0.28], -0.3: [-0.28], 0.2:
>> [-0.15], -0.1: [-0.04], 1.1: [-2.34], -180.0: [-65.0], -0.2: [-0.15], 1.2:
>> [-3.69], -40.0: [-42.0], 0.4: [-0.39], -5.5: [-25.0], -1.5: [-10.0], -20.0:
>> [-39.0], 0.9: [-0.55], -3.5: [-21.0], -1.9: [-21.0], -15.0: [-39.0], -13.0:
>> [-38.0], 1.3: [-5.39], -1.3: [-5.39], -3.6: [-25.0], -1.0: [-1.31], -1.1:
>> [-2.34]}
>> azlist = [-0.9, -0.5, 3.5, 1.4, 5.5, 0.0, 1.9, 13.0, 15.0, 3.6, 20.0,
>> -1.4, 90.0, -0.4, 0.5, 0.1, 1.0, -90.0, 40.0, 180.0, 1.5, -1.2, 0.3, -0.3,
>> 0.2, -0.1, 1.1, -180.0, -0.2, 1.2, -40.0, 0.4, -5.5, -1.5, -20.0, 0.9,
>> -3.5, -1.9, -15.0, -13.0, 1.3, -1.3, -3.6, -1.0, -1.1]
>> azlist = [float(i) for i in azlist]
>> closestaz = min(azlist, key=lambda x: abs(x - azdegpattrev))
>> existattn = azattndic[closestaz]
>> siglevfromexist = 34.8 + existattn
>
> The value in existattn is a single element list.  The single element is a
> float, so just refer to it in your calculation, like so:
>
>     siglevfromexist = 34.8 + existattn[0]

But as you do so, remember to wonder why the author of this code
made the elements of azattndic *lists* of values instead of simple
single values.  Then, worry that someday your corrected code, which
uses only the first value of the list, will be handed a list with
several values.  (True, it will execute without exception; but right
now, today, you know that if the list length is not 1, you're
confused.)

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list