Return sublists of List of lists

后端 未结 4 408
盖世英雄少女心
盖世英雄少女心 2021-01-22 13:45

Well, I have this example:

mylist = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4,          


        
相关标签:
4条回答
  • 2021-01-22 14:19

    A functional approach:

    map(operator.itemgetter(slice(0, 5)), mylist)
    
    0 讨论(0)
  • 2021-01-22 14:28

    Well, you could do the same using list comprehension so at least it would get a bit shorter.

    return [x[:5] for x in mylist]
    

    Or if making your function a generator instead, you could also yield the individual elements:

    for x in mylist:
        yield x[:5]
    
    0 讨论(0)
  • 2021-01-22 14:32

    You should probably use generators for the inner lists as well, if you are trying to get the process to scale :

    g = lambda k: (k[i] for i in range(5))
    for x in mylist:
        yield g(x)
    
    0 讨论(0)
  • 2021-01-22 14:36

    Another way to achieve it:

    return map(lambda lst: lst[:5], mylist)
    
    0 讨论(0)
提交回复
热议问题