Python - Parsing Columns and Rows -


i running trouble parsing contents of text file 2d array/list. cannot use built-in libraries, have taken different approach. text file looks like, followed code

 1,0,4,3,6,7,4,8,3,2,1,0 2,3,6,3,2,1,7,4,3,1,1,0 5,2,1,3,4,6,4,8,9,5,2,1 
def twodarray():     network = [[]]             filename = open('twodarray.txt', 'r')     line in filename.readlines():         col = line.split(line, ',')         row = line.split(',')      network.append(col,row)              print "network = "     print network          if __name__ == "__main__":     twodarray() 

i ran code got error:

traceback (most recent call last):   file "2darray.py", line 22, in <module>     twodarray()   file "2darray.py", line 8, in twodarray     col = line.split(line, ',') typeerror: integer required 

i using comma separate both row , column not sure how differentiate between 2 - confused why telling me integer required when file made of integers

to directly answer question, there problem following line:

col = line.split(line, ',') 

if check documentation str.split, you'll find description follows:

str.split([sep[, maxsplit]]) 

return list of words in string, using sep delimiter string. if maxsplit given, @ maxsplit splits done (thus, list have @ maxsplit+1 elements). if maxsplit not specified, there no limit on number of splits (all possible splits made).

this not want. not trying specify number of splits want make.


consider replacing loop , network.append this:

for line in filename.readlines():     # line string representing values row     row = line.split(',')     # row list of numbers strings row, such ['1', '0', '4', ...]     cols = [int(x) x in row]     # cols list of numbers row, such [1, 0, 4, ...]     network.append(row)     # put row network, such network [[1, 0, 4, ...], [...], ...] 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -