0

I have a list of list like that :

liste = [["1-2","3-4"],["5-6"]]

I would like to write in a file like that :

1-2,3-4|5,6

I try this :

for l in liste:
    sortie.write(",".join(l)+"|")

but it writes:

1-2,3-4|5,6|

How can I delete (or don't write) the last pipe ?

3 Answers 3

1

Use a list comprehension to join your lists in one .write() call:

sortie.write('|'.join([','.join(l) for l in liste]))

This replaces your for loop over liste.

Demo:

>>> liste = [["1-2","3-4"],["5-6"]]
>>> '|'.join([','.join(l) for l in liste])
'1-2,3-4|5-6'
Sign up to request clarification or add additional context in comments.

3 Comments

that's neat, I'm afraid I don't understand why the first part of the nesting works: [','.join(l) for l in liste] . When i see this the result I expect is ['1-2,3-4,5-6'] nor do I get why it doesn't work, in the interpreter, when I omit the [] ','.join(l) for l in liste
@Dee: there are nested lists; each list object in liste needs joining first (using ','), before joining those results with '|'.
yes, the logic I grasp, I'm failing to see how the result is reached though. weird I know. I think looking at it again now, if I imagine the removal of the quotes as more fundamental I start to see the elements coming together the way they appropriately do, rather than the commas being the key - even though they are the key. my mind block, must be some childhood trauma inhibiting me ;)
1

Nested joins:

s = '|'.join(','.join(l) for l in liste)

Comments

0
>>> lines = []
>>> for line in liste:
...     lines.append(','.join(map(str, line)))
... 
>>> print '|'.join(lines)
1-2,3-4|5-6
>>> 

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.