Explicitly select items from a list or tuple

前端 未结 8 1793

I have the following Python list (can also be a tuple):

myList = [\'foo\', \'bar\', \'baz\', \'quux\']

I can say

>>&g         


        
8条回答
  •  有刺的猬
    2020-11-27 11:15

    It isn't built-in, but you can make a subclass of list that takes tuples as "indexes" if you'd like:

    class MyList(list):
    
        def __getitem__(self, index):
            if isinstance(index, tuple):
                return [self[i] for i in index]
            return super(MyList, self).__getitem__(index)
    
    
    seq = MyList("foo bar baaz quux mumble".split())
    print seq[0]
    print seq[2,4]
    print seq[1::2]
    

    printing

    foo
    ['baaz', 'mumble']
    ['bar', 'quux']
    

提交回复
热议问题