python - Problems with iterating 'int' values when converting for loop to while loop -


i have been set task of creating program extracts data text file between 2 key words using while loop creating list of tuples (with date being list , data value integer)

e.g.

<begin step data> 2001-01-01,12776 2001-01-02,15128 <end step data> 

extract format [('2001-01-01', 12776), ('2001-01-02', 15128)]

i started off solving for loop make easier, ended piece of code gives me right answer:

def read_records_from_file(filename):      """ bla """      mylist = []     line = open(filename).read()     start = '<begin step data>'     end = '<end step data>'     startpos = line.find(start) + len(start)     endpos = line.find(end, startpos)     data = line[startpos:endpos]     mylist.append(data.split())      desired = []     element in mylist[0]:         element = element.split(',')          desired.append((element[0],int(element[1])))        return desired 

this approach converting while loop:

def read_records_from_file(filename):      """ bla """      mylist = []     line = open(filename).read()     start = '<begin step data>'     end = '<end step data>'     startpos = line.find(start) + len(start)     endpos = line.find(end, startpos)     data = line[startpos:endpos]     mylist.append(data.split())      desired = []      element = 0      while element < len(mylist[0]):         element = element.split(',')         desired.append((element[0],int(element[1])))          element += 1      return desired 

but gives me errors 'int' object has no attribute 'split'. confused how me changing while loop making read int instead of list.

for statement can converted in while as:

element = 0 while element < len(mylist[0]):     data = mylist[0][element].split(',')     desired.append((data[0],int(data[1])))      element += 1 

you can try pythonic way:

>>> data = "2001-01-01,12776 2001-01-02,15128" >>> data = data.split() >>> print data ['2001-01-01,12776', '2001-01-02,15128'] >>> final_data = [] >>> d in data:     temp = tuple(d.split(","))     temp_tuple = (temp[0],int(temp[1]))     final_data.append(temp_tuple)     >>> print final_data [('2001-01-01', '12776'), ('2001-01-02', '15128')] 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -