Merging a list of lists

前端 未结 4 899
醉酒成梦
醉酒成梦 2020-12-19 08:05

How do I merge a list of lists?

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

into

[\'A\', \'B\', \         


        
相关标签:
4条回答
  • 2020-12-19 08:14

    Use itertools.chain:

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

    Wrapping the elements in HTML can be done afterwards.

    >>> ['<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 generate valid HTML you may also need to HTML escape some of the content in your strings.

    0 讨论(0)
  • 2020-12-19 08:20

    To concatenate the lists, you can use sum

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

    To add the HTML tags, you can use a list comprehension.

    html_values = ['<tr>' + i + '</tr>' for i in values]
    
    0 讨论(0)
  • 2020-12-19 08:27

    Don't use sum(), it is slow for joining lists.

    Instead a nested list comprehension will work:

    >>> 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 _]
    

    The advice to use itertools.chain was also good.

    0 讨论(0)
  • 2020-12-19 08:38
    import itertools
    
    print [('<tr>%s</tr>' % x) for x in itertools.chain.from_iterable(l)]
    

    You can use sum, but I think that is kinda ugly because you have to pass the [] parameter. As Raymond points out, it will also be expensive. So don't use sum.

    0 讨论(0)
提交回复
热议问题