0

I want to convert list of floats into integers. My code

import math

data1 = [line.strip() for line in open("/home/milenko/Distr70_linux/Projects/Tutorial_Ex3/myex/base.txt", 'r')]
print type(data1)
data1c = [int(math.floor(i)) for i in data1]

print data1c[0]

What should I change? File is huge,just couple of lines

1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121

2 Answers2

6

You need to first cast to float:

[int(float(i)) for i in data1]

calling int will floor the number for you:

In [8]: int(float("1.23456e+03"))
Out[8]: 1234

You can do it all in the file logic:

with open("/home/milenko/Distr70_linux/Projects/Tutorial_Ex3/myex/base.txt", 'r') as f:
   floored = [int(float(line)) for line in f]

It is good practice to use with to open your files, it will handle the closing of your files for you. Also int and float can handle leading or trailing white space so you don't need to worry about using strip.

Also if you were just wanting to pull the floats and not also floor, map is a nice way of creating a list of floats, ints etc.. from a file or any iterable:

 floored = list(map(float, f))

Or using python3 where map returns an iterator, you could double map:

floored = list(map(int, map(float, f)))

The equivalent code in python2 would be using itertools.imap

from itertools import imap

floored = map(int, imap(float, f))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

Data read from files are always of str type where as parameter required for math.floor is a float

So you need convert it into float

data1c = [int(float(i)) for i in data1]
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65