Python创建由slice组成的元组:基于位置生成slice并拼接为元组的实现方法
Hey there! Let's fix up your code and get that tuple of slices working properly. First, a quick note: your original code has a small syntax error—since sl is a tuple, you need to access elements with square brackets sl[i] instead of parentheses sl(i).
Solution 1: Build a List First, Convert to Tuple
The most straightforward way is to collect each slice in a list as you loop, then convert the list to a tuple at the end:
sl = (0.1, 0.2, 0.3) slice_collection = [] for i in range(len(sl)): if i == 0: current_slice = slice(0, sl[i], 0.1) else: current_slice = slice(sl[i-1], sl[i], 0.1) slice_collection.append(current_slice) # Convert the list to a tuple slices_tuple = tuple(slice_collection)
Solution 2: Use a Generator Expression (More Concise)
For a shorter, more Pythonic approach, you can use a generator expression directly inside the tuple() constructor. This avoids explicitly creating a list:
sl = (0.1, 0.2, 0.3) slices_tuple = tuple( slice(0, sl[i], 0.1) if i == 0 else slice(sl[i-1], sl[i], 0.1) for i in range(len(sl)) )
Important Note About Float Step Sizes
Keep in mind that Python's built-in slice object doesn't support floating-point step sizes for indexing standard sequences (like lists or tuples). If you try to use these slices on a regular list, you'll get a TypeError because indices must be integers.
If you're working with numerical arrays (e.g., using NumPy), NumPy does support floating-point step sizes in its slicing, so these slices will work as expected with NumPy arrays.
内容的提问来源于stack exchange,提问作者Mateus Forcelini

