Accessing non-consecutive elements of a list or string in python

后端 未结 5 2006
难免孤独
难免孤独 2020-12-28 15:14

As far as I can tell, this is not officially not possible, but is there a \"trick\" to access arbitrary non-sequential elements of a list by slicing?

For example:

5条回答
  •  Happy的楠姐
    2020-12-28 16:02

    If you can use numpy, you can do just that:

    >>> import numpy
    >>> the_list = numpy.array(range(0,101,10))
    >>> the_indices = [2,5,7]
    >>> the_subset = the_list[the_indices]
    >>> print the_subset, type(the_subset)
    [20 50 70] 
    >>> print list(the_subset)
    [20, 50, 70]
    

    numpy.array is very similar to list, just that it supports more operation, such as mathematical operations and also arbitrary index selection like we see here.

提交回复
热议问题