How can I iterate through a python 2D list and delete/replace characters from a specific column? -


i have following 2d list

data = [['2013-02-03', 'london', 'miles', '25'], ['2013-02-03', 'newcastle', 'miles', '25'], ['2013-02-03', 'birmingham', 'miles', '62']] 

i need able remove of '' in column e.g last column below can pass 2d list javascript function in text file.

data = [['2013-02-03', 'london', 'miles', 25], ['2013-02-03', 'newcastle', 'miles', 25], ['2013-02-03', 'birmingham', 'miles', 62]] 

i have function , can result on single value

r = "['2013-02-03', 'london', 'miles', '25']"   def rreplace(s, old, new, occurrence):     li = s.rsplit(old, occurrence)     return new.join(li)      rreplace(p, "'", '', 2)  "['2013-02-03', 'feltham', 'less_than_one_day', 25]," 

can suggest better way achieve result?

i have tried number of ways using: loops, map/lambda , iter, can loop through list or change element in single list can't both , output result.

just process list of values python:

for row in data:     row[-1] = int(row[-1]) 

this replaces each last element in data nested lists integer equivalent.

next, use json module turn valid javascript:

import json  r = json.dumps(data) 

json subset of javascript after all.

quick demo:

>>> data = [['2013-02-03', 'london', 'miles', '25'], ['2013-02-03', 'newcastle', 'miles', '25'], ['2013-02-03', 'birmingham', 'miles', '62']] >>> row in data: ...     row[-1] = int(row[-1]) ...  >>> data [['2013-02-03', 'london', 'miles', 25], ['2013-02-03', 'newcastle', 'miles', 25], ['2013-02-03', 'birmingham', 'miles', 62]] >>> import json >>> json.dumps(data) '[["2013-02-03", "london", "miles", 25], ["2013-02-03", "newcastle", "miles", 25], ["2013-02-03", "birmingham", "miles", 62]]' 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -