Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Joining Multiple Lists to one single Sentence

Tags:

python

join

list

Howdy, I've got multiple lists. For example:

[u'This/ABC']
[u'is/ABC']
[u'not/ABC']
[u'even/ABC']
[u'close/ABC']
[u'to/ABC']
[u'funny/ABC']
[u'./ABC']

[u'O/ABC']
[u'noez/ABC']
[u'!/ABC']

I need to join this List to

This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC

O/ABC noez/ABC !/ABC

How do I do that please? Yes, with the empty space in between!


1 Answers

If you put them all in a list, for example like this:

a = [
    [u'This/ABC'],
    [u'is/ABC'],
    ...
]

You can get your result by adding all the lists and using a regular join on the result:

result = ' '.join(sum(a, []))

After re-reading the question a couple of times, I suppose you also want that empty line. This is just more of the same. Add:

b = [
    [u'O/ABC'],
    [u'HAI/ABC'],
    ...
]

lines = [a, b]

result = '\n\n'.join([' '.join(sum(line, [])) for line in lines])
like image 63
Magnus Hoff Avatar answered Mar 02 '26 22:03

Magnus Hoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!