convert string containing list to list (or tuple) type

P

Poppy

I'm reading from a database a column that has a list of codes (comma
seperated). When I read in the list I have a single value, see code sample
below values for a, b, and c. These represent possible values in my
database. I need to loop through each value so I can expand my data from
this compressed view.

My code below works and creates my desired output but I believe there must
be a better way this is very messy. My messy function that I'd like to
replace is lst_codes(codes). Any alternative suggestions?

this is what I begin with
a = ',P,'
b = ',I,G,AQ,ET,K,BF,'
c = ',DZ,'
this is what I want (lists or tuples are fine)
['P']
['I', 'G', 'AQ', 'ET', 'K', 'BF']
['DZ']


def lst_codes(codes):
""" turn a string of comma seperated codes into a real list object """
i = 0
lstD = []
while i < len(codes):
a = codes
b = ","
if (i + 1) < len(codes):
b = codes[i + 1]
i = i + 1
else:
b = ","

if b <> ",":
lstD.append(a + b)
i = i + 2
else:
lstD.append(a)
i = i + 1
return lstD


a = ',P,'
b = ',I,G,AQ,ET,K,BF,'
c = ',DZ,'

for ea in (a,b,c):
print lst_codes(ea.strip(","))
 
P

Poppy

Arrgh. One of those days where I find an answer just after posting. I spend
hours on the code below only to find I don't know how to use split to it's
fullest.
['I', 'G', 'AQ', 'ET', 'K', 'BF']

Poppy said:
I'm reading from a database a column that has a list of codes (comma
seperated). When I read in the list I have a single value, see code sample
below values for a, b, and c. These represent possible values in my
database. I need to loop through each value so I can expand my data from
this compressed view.

My code below works and creates my desired output but I believe there must
be a better way this is very messy. My messy function that I'd like to
replace is lst_codes(codes). Any alternative suggestions?

this is what I begin with
a = ',P,'
b = ',I,G,AQ,ET,K,BF,'
c = ',DZ,'
this is what I want (lists or tuples are fine)
['P']
['I', 'G', 'AQ', 'ET', 'K', 'BF']
['DZ']


def lst_codes(codes):
""" turn a string of comma seperated codes into a real list object """
i = 0
lstD = []
while i < len(codes):
a = codes
b = ","
if (i + 1) < len(codes):
b = codes[i + 1]
i = i + 1
else:
b = ","

if b <> ",":
lstD.append(a + b)
i = i + 2
else:
lstD.append(a)
i = i + 1
return lstD


a = ',P,'
b = ',I,G,AQ,ET,K,BF,'
c = ',DZ,'

for ea in (a,b,c):
print lst_codes(ea.strip(","))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top