Re: converting a sed / grep / awk / . . . bash pipe line into python
- From: Roy Smith <roy@xxxxxxxxx>
- Date: Wed, 03 Sep 2008 07:54:46 -0400
In article <g9ldi5$2ea$03$1@xxxxxxxxxxxxxxxxx>,
Peter Otten <__peter__@xxxxxx> wrote:
Without them it looks better:
import sys
for line in sys.stdin:
try:
a, b = map(int, line.split(None, 2)[:2])
except ValueError:
pass
else:
if a + b == 42:
print b
I'm philosophically opposed to one-liners like:
a, b = map(int, line.split(None, 2)[:2])
because they're difficult to understand at a glance. You need to visually
parse it and work your way out from the inside to figure out what's going
on. Better to keep it longer and simpler.
Now that I've got my head around it, I realized there's no reason to make
the split part so complicated. No reason to limit how many splits get done
if you're explicitly going to slice the first two. And since you don't
need to supply the second argument, the first one can be defaulted as well.
So, you immediately get down to:
a, b = map(int, line.split()[:2])
which isn't too bad. I might take it one step further, however, and do:
fields = line.split()[:2]
a, b = map(int, fields)
in fact, I might even get rid of the very generic, but conceptually
overkill, use of map() and just write:
a, b = line.split()[:2].
a = int(a)
b = int(b)
- Follow-Ups:
- Re: converting a sed / grep / awk / . . . bash pipe line into python
- From: bearophileHUGS
- Re: converting a sed / grep / awk / . . . bash pipe line into python
- From: Peter Otten
- Re: converting a sed / grep / awk / . . . bash pipe line into python
- References:
- Re: converting a sed / grep / awk / . . . bash pipe line into python
- From: Peter Otten
- Re: converting a sed / grep / awk / . . . bash pipe line into python
- Prev by Date: Re: Python IDEs with F5 or hotkey shell interaction
- Next by Date: Re: converting a sed / grep / awk / . . . bash pipe line into python
- Previous by thread: Re: converting a sed / grep / awk / . . . bash pipe line into python
- Next by thread: Re: converting a sed / grep / awk / . . . bash pipe line into python
- Index(es):
Relevant Pages
|