For input file separate by space/tab like:
1 2 3
4 5 6
7 8 9
How to read the line and split the integers, then save into either lists or tuples? Thanks.
data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
One way to do this, assuming the sublists are on separate lines:
with open("filename.txt", 'r') as f:
data = [map(int, line.split()) for line in f]
Note that the with
statement didn't become official until Python 2.6. If you are using an earlier version, you'll need to do
from __future__ import with_statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With