I am a fresher to python.
I am trying to get [[7, 1], [8], [4, 0, 5]]
this as result but I am keep getting [['7, 1'], ['8'], ['4, 0, 5']]
.
def nested_list(f):
opener = open(f,"r")
lst =[lin.strip().split(" , ") for lin in opener]
return lst
How can I correct my code?
You need to cast it into an int
from string
. One way to do it is using map
def nested_list(f):
opener = open(f,"r")
lst = [map(int, lin.strip().split(" , ")) for lin in opener]
return lst
If your question accurately represents the file, it looks like the following, with one space after the comma:
7, 1
8
4, 0, 5
Use this:
def nested_list(f):
with open(f) as opener: # so the file is closed automatically.
return [[int(x) for x in lin.strip().split(', ')] for lin in opener]
In place of int you can use eval function in both above answer.Int function give error when your string contain special char while eval work smoothly
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.