简体   繁体   中英

A Question regarding Choosing subarray in Python

In the following code in python:

import numpy as np
a =  np.random.normal(2, 0.1, 10)
c = [0,1,2,3,4,5,6,7,8,9]
b = [2,4]
print(a[b])
print(c[b])

Why print(a[b]) can be executed but an error message is shown for print(c[b])?

This type of indexing only works for numpy.ndarray and c is just a python list so you can't index it like numpy.ndarray . You can convert it to numpy array first then use your indexing.

c = np.array(c)

In python, list accepts integer based index.

To execute

## Replace print(c[b]) with following line
print(c[b[0]:b[1])

Output of the above code

[2, 3]

The C list is being iterated from index 2 to index 3. As python iterated upto end-1 index.

Eg c[2:4] only index 2 and index 3 will be considered.

When you use bracket on an object like this:

a[b]

You are calling the function __getitem__ of the class of the object a with b as the argument. See this for more detailed of the function.

Now if a[b] does not show an error while c[b] raises one this means that the implementation of the method __getitem__ for the class of a is handling the type of b and the implementation of this method for the class of c does not. This behaviour is exactly the same for every functions, the call is just a bit hidden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM