Any way to write this in one line in Python, or even better, as an expression instead of a statement?
parts = ['0', '1', 'None', '5', '4']
[int(p) for p in parts]
This of course gives an error,
ValueError: invalid literal for int() with base 10: 'None'
So:
[p=='None' and None or int(p) for p in parts]
Doesn't work because you can't use None
with the and/or construct reliably. (Even if p=='None'
is true, None
is equivalent to false so it goes to the or
part.)
[int(p) if p=='None' else None for p in parts]
Also doesn't work. I guess it evaluates int(p)
before the conditions? (Seems odd semantics.)
a = []
for p in parts:
if p=='None': k = None; else: k = int(p)
a.append(k)
Nope, invalid syntax.
a = []
for p in parts:
if p=='None':
k = None;
else:
k = int(p)
a.append(k)
Ah! Finally. But isn't there a shorter way to write such a simple loop?