Reversed array slice including the first element [duplicate]

2024/11/16 1:42:52

Let's say I have:

>>> a = [1, 2, 3, 4]

And I want to get a reversed slice. Let's say I want the 1st and 0th elements given start_idx = 1 and stop_idx = 0:

[2, 1] 

Using the slice notation:

a[x:y:z]

What values do I use for x, y, and z using start_idx and stop_idx?

I've tried:

>>> a[start_idx:stop_idx:-1]
[2]
>>> a[start_idx:stop_idx-1:-1]
[]

Differentiation:

This question is about a slice with a negative step where the both start and end indexed elements should be included (like a closed interval in math), and the slice end index is dynamically calculated.

Understanding Python's slice notation is a generic generic question on notation: what x, y, and z mean in a[x:y:z]. It doesn't mention the reversal case.

This question differs from the other flagged duplicates as it deals with the general case where the reversed slice begin and end indices are either calculated or given by variables rather than hard coded.

Answer

You can omit the second index when slicing if you want your reversed interval to end at index 0.

a = [1, 2, 3, 4]
a[1::-1] # [2, 1]

In general whenever your final index is zero, you want to replace it by None, otherwise you want to decrement it.

Due to indexing arithmetic, we must treat those cases separately to be consistent with the usual slicing behavior. This can be done neatly with a ternary expression.

def reversed_interval(lst, i=None, j=None):return lst[j:i - 1 if i else None:-1]reversed_interval([1, 2, 3, 4], 0, 1) # [2, 1]
https://en.xdnf.cn/q/71723.html

Related Q&A

Problem using py2app with the lxml package

I am trying to use py2app to generate a standalone application from some Python scripts. The Python uses the lxml package, and Ive found that I have to specify this explicitly in the setup.py file that…

How to run TensorFlow on AMD/ATI GPU?

After reading this tutorial https://www.tensorflow.org/guide/using_gpu I checked GPU session on this simple code import numpy as np import matplotlib.pyplot as plt import tensorflow as tfa = tf.constan…

Pure virtual function call

Im using boost.python to make python-modules written in c++. I have some base class with pure virtual functions which I have exported like this:class Base {virtual int getPosition() = 0; };boost::pytho…

Expected String or Unicode when reading JSON with Pandas

I try to read an Openstreetmaps API output JSON string, which is valid.I am using following code:import pandas as pd import requests# Links unten minLat = 50.9549 minLon = 13.55232# Rechts oben maxLat …

How to convert string labels to one-hot vectors in TensorFlow?

Im new to TensorFlow and would like to read a comma separated values (csv) file, containing 2 columns, column 1 the index, and column 2 a label string. I have the following code which reads lines in th…

Pandas dataframe boolean mask on multiple columns

I have a dataframe (df) containing several columns with an actual measure and corresponding number of columns (A,B,...) with an uncertainty (dA, dB, ...) for each of these columns:A B dA dB …

Which of these scripting languages is more appropriate for pen-testing? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Keras: Optimal epoch selection

Im trying to write some logic that selects the best epoch to run a neural network in Keras. My code saves the training loss and the test loss for a set number of epochs and then picks the best fitting …

error in loading pickle

Not able to load a pickle file. I am using python 3.5import pickle data=pickle.load(open("D:\\ud120-projects\\final_project\\final_project_dataset.pkl", "r"))TypeError: a bytes-lik…

How to test if a webpage is an image

Sorry that the title wasnt very clear, basically I have a list with a whole series of urls, with the intention of downloading the ones that are pictures. Is there anyway to check if the webpage is an i…