Ho una lista di listePython Forza List Indice di Gamma Exception
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Voglio che il codice per lanciare un Array Out of Bounds Eccezione simile a come si fa in Java quando l'indice è fuori portata . Ad esempio,
x[0][0] # 1
x[0][1] # 2
x[0-1][0-1] # <--- this returns 9 but I want it to throw an exception
x[0-1][1] # <--- this returns 7 but again I want it to throw an exception
x[0][2] # this throws an index out of range exception, as it should
Se viene generata un'eccezione, voglio che ritorni 0.
try:
x[0-1][0-1] # I want this to throw an exception
except:
print 0 # prints the integer 0
Credo che fondamentalmente in qualsiasi momento l'indice è negativo, un'eccezione.
Il numero -1 non è un indice non valido per un elenco, però. Restituisce solo l'ultimo elemento ... Quindi perché lo fa attraverso un errore? – Ben
L'indicizzazione negativa è supportata in Python. – letsc
Gli indici negativi hanno uno scopo particolare, molto utile in Python: indicizzazione dalla fine di un 'list' (o' str', o cosa avete). Voler eliminare questo comportamento probabilmente significa che dovresti tornare indietro e ripensare alla logica del tuo programma. – TigerhawkT3