Python’s map power – newbies

There are some methods that I love, one of them is map. Surely you already know!

Imagine that you want to read the line cpu in the file /proc/stat

The file looks similar to this:

cpu 5513 0 7271 2832299 15350 1 1327 0 0 0

cpu1 xxx xxx xxx xxx xxx xxx xxx

  1. We open the file with open and assign it to a file object with (‘as’)
  2. Loop the file object (st)
  3. If the line startswith(‘cpu ‘) then we continue. (I left a space on the right of cpu, because in the file also we have cpu1, cpu2, and I only need ‘cpu’.
  4. I assign the result of map. We split the line starting in index 1 and we map the elements executing float in every element.

 

1
2
3
4
5
with open('/proc/stat', 'r') as st:
    for line in st:
        if line.startswith('cpu '):
            line_split = map(float, line.strip().split()[1:])
    print line_split

Other way to do it:  with a list comprehension:

1
line_split = [ int(x) for x in line.strip().split()[1:] ]