从列表列表中删除外部列表

时间:2018-05-14 17:20:28

标签: python python-3.x

如何删除此外层?

class BlogListView(ListView, CategoryMixin):
    model = Event
    template_name = 'pages/home.html'

    def get_context_data(self, **kwargs):
        ctx = super(BlogListView, self).get_context_data(**kwargs)
        ctx['view_specific'] = 'something'
        return ctx

... 

有很多帖子详细说明如何拼合列表列表(基本上与删除外层相同),但我找不到列表列表的任何内容

谢谢!

1 个答案:

答案 0 :(得分:0)

要删除一个图层,只需应用chain.from_iterable

即可
>>> items = [
...     [['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH']],
...     [['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]
... ]
>>> from itertools import chain
>>> items2 = list(chain.from_iterable(items))
>>> items2
[['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH'], ['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]
>>> items3 = list(chain.from_iterable(items2)) 
>>> items3 
['SKU', 'DHF', 'KSD', 'KUD', 'HFK', 'SDJ', 'UDH', 'FKS', 'DJH', 'KUG', 'UJY', 'FUY', 'UGU', 'JYF', 'UYF', 'GUJ', 'YFU', 'YFG']