Re: converting a sed / grep / awk / . . . bash pipe line into python



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)
.



Relevant Pages

  • Re: converting a sed / grep / awk / . . . bash pipe line into python
    ... import sys ... except ValueError: ... I'm philosophically opposed to one-liners ... Now that I've got my head around it, I realized there's no reason to make ...
    (comp.lang.python)
  • Re: screen power problem
    ... What was the reason for the rebuild?, if it was a new mobo check Asus for ... bios update. ... I sometimes find on one of my sys when the monitor wont switch off ... In particular: ASUS mobo, ...
    (microsoft.public.win2000.general)
  • gnome, solaris, linux, oh my....
    ... solaris environment are crashing when switching between them. ... The reason this happens is because .gnome in their home dir is used by ... anyone has done an NFS version of @SYS? ...
    (comp.arch.storage)
  • Re: Where is the performance bottleneck?
    ... > sys 0m0.151s ... the reason i found is... ... > but still, I can get linear speed at 4 DISKS, then no speed gain when ... send the line "unsubscribe linux-kernel" in ...
    (Linux-Kernel)