I'm new at Python and I have an assginment which is read a file and convert it to matrix. My file is:
n 5
0 -- 3
0 -- 4
1 -- 2
1 -- 3
2 -- 4
3 -- 3
First of all,I have to make a "5X5" matrix. I read 5 like this:
f = open("graph.txt")
mylist = f.readlines()
a = mylist[0][2]
When say print a it prints 5. In order to make a matrix I need to convert this string to integer. However, when I used int(a) function, it remained a str. How can I change it to integer permanently?
2 Answers 2
int creates a new value but does not change the original one. So, to actually change the value, you must do something like
list[0][2] = int(list[0][2])
Comments
use the int() constructor to assign to a:
a = int(list[0][2])
Note that this will raise an exception if the string cannot be converted to int.
.split()method to split strings into chunks based on whitespace. That looks like a tool you're going to need.mylist = [line.strip().split() for line in f].