Dan McGrath
Dan McGrath

Reputation: 42018

Converting from nested lists to a delimited string

Disclaimer: I'm new to Python.

I have an external service that sends data to us in a delimited string format. It is lists of items, up to 3 levels deep. Level 1 is delimited by '|'. Level 2 is delimited by ';' and level 3 is delimited by ','. Each level or element can have 0 or more items. An simplified example is:
a,b;c,d|e||f,g|h;;

We have a function that converts this to nested lists which is how it is manipulated in Python.

def dyn_to_lists(dyn):  
    return [[[c for c in b.split(',')] for b in a.split(';')] for a in dyn.split('|')]

For the example above, this function results in the following:

>>> dyn = "a,b;c,d|e||f,g|h;;"
>>> print (dyn_to_lists(dyn))
[[['a', 'b'], ['c', 'd']], [['e']], [['']], [['f', 'g']], [['h'], [''], ['']]]

Now, I can write a looping construct to convert this back into the delimited format, but it would be messy. Is there a more Python-like way to write a lists_to_dyn(lists) function?

Upvotes: 2

Views: 228

Answers (1)

dparpyani
dparpyani

Reputation: 2493

It is similar to your other method:

def lists_to_dyn(lst):
    return '|'.join(';'.join(','.join(lst3) for lst3 in lst2) for lst2 in lst)

Upvotes: 5

Related Questions