4

I have a list of lists in python looking like this:

[['a', 'b'], ['c', 'd']]

I want to come up with a string like this:

a,b;c,d

So the lists should be separated with a ; and the values of the same list should be separated with a ,

So far I tried ','.join([y for x in test for y in x]) which returns a,b,c,d. Not quite there, yet, as you can see.

3
  • "So the lists should be separated with a ; and the values of the same list should be separated with a ," - that's not a python list then. It's a string Commented Jun 17, 2015 at 9:07
  • 2
    ';'.join(','.join(xs) for xs in lst) Commented Jun 17, 2015 at 9:08
  • yes, the final output should be a string. will update the question accordingly to make that clear. Commented Jun 17, 2015 at 9:08

3 Answers 3

9
";".join([','.join(x) for x in a])
Sign up to request clarification or add additional context in comments.

2 Comments

my actual data contains float values :/ and python now errors TypeError: sequence item 0: expected str instance, float found...
okay in that case i need to use this code: ";".join([','.join(map(str, x)) for x in value])
7
>>> ';'.join(','.join(x) for x in [['a', 'b'], ['c', 'd']])
'a,b;c,d'

Comments

1

To do it functionally you could use map:

l = [['a', 'b'], ['c', 'd']]


print(";".join(map(".".join, l)))
a.b;c.d

Comments

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.