Question

Input: file with several lines of strings, each line is a separate string:

1234,123,345 
4567,56,76 
1029,192,13

Output: list of lists, where each line is a separate list

[[1234,123,345],[4567,56,76],[1029,192,13]]

Usually I have been able to do these because the input did not have commas and were just spaced out, but each line is one string, so it is throwing me off.

So far, I have:

with open("file.txt") as f:
    info = f.readlines()
solution = []
for line in info:
    solution.append([line])
print solution

But this yields:

[['1234,123,345\n'],['4567,56,76\n'],['1029,192,13\n']]

I have an idea for a fix where I do another for loop, get each character, and append each non-comma to another array and then convert to int. But this sounds complex and the newline tag was confusing me as well.

Was it helpful?

Solution

I have an idea for a fix where I do another for loop, get each character, and append each non-comma to another array and then convert to int. But this sounds complex…

You're right—that would work, but it's not the easiest way to do it.

Just use the split method on strings, like this:

for line in info:
    solution.append(line.split(","))

Now, instead of each line being ['1234,123,345\n'], it will be ['1234', '123', '345\n'].

This gets you close, but those are still strings, not ints. An inner loop to convert each one to an int, just as you suggested, will work great. But it might be easier to read with a for loop in a list comprehension, rather than in a for statement. Like this:

for line in info:
    solution.append([int(number) for number in line.split(",")])

If you don't understand the comprehension, here it is as a statement:

for line in info:
    numbers = []
    for number in line.split(","):
        numbers.append(int(number))
    solution.append(numbers)

And, since the int function can ignore whitespace, int('345\n') is 345, so you don't have to do anything else.

But if you did have to do something else, rstrip would be the easiest answer: it removes all whitespace from the end of a string. So:

for line in info:
    solution.append([int(number) for number in line.rstrip().split(",")])

OTHER TIPS

You can strip the new line character, with rstrip and then split the string based on ,. Next you can convert the strings to numbers with int and map function.

with open("file.txt") as f:
    print [map(int, line.rstrip().split(",")) for line in f]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top