I have a file format like this:
9 8 1
3 4 1
...
...
Now, I want to get each line as three integers.
When I used
for line in f.readlines():
print line.split(" ")
The script printed this:
['9', '8', '1\r\n']
['3', '4', '1\r\n']
...
...
How can I get each line as three integers?
Using the code you have and addressing your specific question of how to convert your list to integers:
You can iterate through each line and convert the strings to
intwith the following example using list comprehension:Given:
then:
will yield a list of integers
that you can then access via subscripts (0 to 2). e.g.
int_list[0]contains3,int_list[1]contains4,etc.
A more streamlined version for your consideration:
The advantage of using
withis that it will automatically close your file for you when you are done, or if you encounter an exception.UPDATE:
Based on your comments below, if you want the numbers in 3 different variables, say
a,bandc, you can do the following:and get this:
This counts on there being 3 numbers on each line.
Aside:
Note that in place of “list comprehension” (LC) you can also use a “generator expression” (GE) of this form:
for your particular problem with 3 integers this doesn’t make much difference, but I show it for completeness. For larger problems, LC requires more memory as it generates a complete list in memory at once, while GE generate a value one by one as needed. This SO question Generator Expressions vs. List Comprehension will give you more information if you are curious.