Python Style Question

Anton anton.schattenfeld at gmail.com
Wed Oct 29 20:09:00 CET 2014


On Wednesday, October 29, 2014 4:43:33 AM UTC-7, Rafael Romero Carmona wrote:
> Hi, first in Python 2.7.6 and Python 3.4.0 list haven't got any add
> function but they have append.
You are right, in my original code I use set instead of array, so it should be either values = set() or values.append() in the original code.
> 
> I think you could do better with something like
> 
> ==========
> import json
> l = [1, -1, 0, '1', '-1', '0', json.dumps(-1), json.dumps(1),
> json.dumps(0), 'x', 'sqjklsqjk__', (1, 2)]
It should also work with cases like [1, json.dumps('-1')], which is case 3), sorry if it was not clear in the initial post.
> 
> values = []
> 
> for c in l:
>     try:
>         c_int = int(c)
>     except ValueError:
>         pass
>     except TypeError:
>         pass
>     else:
>         values.append(c_int)
>         continue
> print(values)
> ==========
> 
> The code has been tested in Python 2.7.6 and 3.4 and returns [1, -1,
> 0, 1, -1, 0, -1, 1, 0]
> 
> You don't need to do two try because you can process both exceptions
> in the same way. You don't really need to do json.loads because if you
> have a json string which is an integer, you could do that directly
> with int(c) which can take a string and transform in an integer.
In case of 3) an element can be a string like '"1"', which will fail int(...), in this case it tries to parse it with json.





More information about the Python-list mailing list