Combining a List of Lists

How to merge a list of lists?

[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]

at

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Even better, if I can add a value at the beginning and end of each element before merging lists, for example with html tags.

ie, the end result is:

['<tr>A</tr>', '<tr>B</tr>', '<tr>C</tr>', '<tr>D</tr>', '<tr>E</tr>', '<tr>F</tr>', '<tr>G</tr>', '<tr>H</tr>', '<tr>I</tr>']
+5
source share
4 answers

To combine lists you can use sum

values = sum([['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']], [])

To add HTML tags, you can use list comprehension.

html_values = ['<tr>' + i + '</tr>' for i in values]
+2
source

Do not use sum (), it is slow to merge lists.

Instead, there will be a nested list comprehension :

>>> x = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
>>> [elem for sublist in x for elem in sublist]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
>>> ['<tr>' + elem + '</tr>' for elem in _]

Recommendations for using itertools.chain were also good.

+8
source
import itertools

print [('<tr>%s</tr>' % x) for x in itertools.chain.from_iterable(l)]

You can use the sum, but I think this is pretty ugly because you need to pass the [] parameter. As Raymond points out, it will also be expensive. Therefore, do not use the amount.

+2
source

Use itertools.chain:

>>> import itertools
>>> list(itertools.chain(*mylist))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Wrapping elements in HTML can be done later.

>>> ['<tr>' + x + '</tr>' for x in itertools.chain(*mylist)]
['<tr>A</tr>', '<tr>B</tr>', '<tr>C</tr>', '<tr>D</tr>', '<tr>E</tr>', '<tr>F</tr>',
'<tr>G</tr>', '<tr>H</tr>', '<tr>I</tr>']

Note that if you are trying to create the correct HTML, you may need the HTML escape part of the content in your lines.

0
source

All Articles