2

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?

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

3 Comments

you don't need to build intermediate lists, generator expressions are sufficient.
Thanks @dparpyani! Compared to what I was playing with, this is very neat. Cheers.
@roippi: List comprehensions are faster than generators for str.join().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.