Sub matrix of a list of lists (without numpy)

前端 未结 4 1399
误落风尘
误落风尘 2020-12-09 12:04

Suppose I have a matrix composed of a list of lists like so:

>>> LoL=[list(range(10)) for i in range(10)]
>>> LoL
[[0, 1, 2, 3, 4, 5, 6, 7,         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 12:48

    In [74]: [row[2:5] for row in LoL[1:4]]
    Out[74]: [[2, 3, 4], [2, 3, 4], [2, 3, 4]]
    

    You could also mimic NumPy's syntax by defining a subclass of list:

    class LoL(list):
        def __init__(self, *args):
            list.__init__(self, *args)
        def __getitem__(self, item):
            try:
                return list.__getitem__(self, item)
            except TypeError:
                rows, cols = item
                return [row[cols] for row in self[rows]]
    
    lol = LoL([list(range(10)) for i in range(10)])
    print(lol[1:4, 2:5])
    

    also yields

    [[2, 3, 4], [2, 3, 4], [2, 3, 4]]
    

    Using the LoL subclass won't win any speed tests:

    In [85]: %timeit [row[2:5] for row in x[1:4]]
    1000000 loops, best of 3: 538 ns per loop
    In [82]: %timeit lol[1:4, 2:5]
    100000 loops, best of 3: 3.07 us per loop
    

    but speed isn't everything -- sometimes readability is more important.

提交回复
热议问题