Python Style Question
Anton
anton.schattenfeld at gmail.com
Wed Oct 29 06:42:22 EDT 2014
Let's say I have an incoming list of values *l*. Every element of *l* can be one of the following options:
1) an integer value
2) a string in form of '<int_value>', e.g. '7'
3) a string with a json serialization of an integer value, e.g. '"7"'
4) something else that should be ignored
I need to transform this list into another list with values from options 1)-3) coerced to int. The code below should do this.
Variant 1
===
values = []
for c in l:
# Case 1) or 2)
try:
c_int = int(c)
except ValueError:
pass
else:
values.add(c_int)
continue
# Case 3)
try:
c_int = int(json.loads(c))
except ValueError:
pass
else:
values.add(c_int)
continue
===
Is this code ugly?
Does it follow EAFP?
Am I missing something in language best practice?
Or maybe below is more preferable way with a nested try...except clause?
Variant 2
===
values = []
for c in l:
# Case 1) or 2)
try:
c_int = int(c)
except ValueError:
# Case 3)
try:
c_int = int(json.loads(c))
except ValueError:
pass
else:
values.add(c_int)
continue
else:
values.add(c_int)
continue
===
Thanks,
Anton.
More information about the Python-list
mailing list