QNA > P > Perché Python Inizia Dall'indice 1 Quando Itera Un Array All'indietro?

Perché Python inizia dall'indice 1 quando itera un array all'indietro?

Non lo fa, inizia da -1.

Ma prima di arrivare a questo, dovremmo notare che sia che stiamo parlando di una lista, di una stringa, di una tupla o di un altro iterabile, gli indici Python sono effettivamente degli offset.

Let’s just use a list (as opposed to an array, which is not a native Python datatype).

  1. >>> thislist = 'zero one two three four'.split() 
  2. >>> thislist 
  3. ['zero', 'one', 'two', 'three', 'four'] 

Vediamo come funziona l'indicizzazione come offset, iniziando da 0. Sono noto per riferirmi al primo elemento di una lista come "elemento zero", ma è certamente imbarazzante. The first element is actually index 0 because it’s precisely zero elements away from the beginning:

  1. >>> print(f'the first element of the list is "{thislist[0]}"') 
  2. the first element of the list is "zero" 

The second element is [1] because it is 1 element away from the beginning:

  1. >>> print(f'the second element of the list is "{thislist[1]}"') 
  2. the second element of the list is "one" 

…and so on.

Ora, Python ha una bella caratteristica, che molti linguaggi non hanno: si possono usare indici negativi per muoversi all'indietro nella lista (o in altri iterabili). Un idioma comune per l'ultimo elemento di un iterabile è [-1]:

  1. >>> print(f'the last element of the list is "{thislist[-1]}"') 
  2. the last element of the list is "four" 

You might be asking about the apparent inconsistency–namely, that when indexing in a forward direction, [0] means the first element, but when indexing in a backward direction, [-1] means the last element.

Ma quale altra scelta abbiamo? [0] significa già il primo elemento, quindi non possiamo usare [-0] per indicare l'ultimo elemento poiché -0 è uguale a 0.

Di Squires Swaynos

È possibile convertire solo un array di dimensioni 1 in uno scalare Python? :: Come trasporre un array in Python
Link utili