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
1
  • You can cast strings to floats. data1 = [float(line.strip()) for line in ...] Commented Mar 29, 2016 at 12:22

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.