如何改进 "slice using a list" 的功能
How to improve a function that "slice using a list"
我的函数使用列表作为切片的索引
slice_ = [1, 2, 0] # start, stop, step
my_list = ["a", "b", "c", "d", "e", "f"]
我想写出更优雅的代码
def slice_function(slice_target, slice_: list[int]):
if len(slice_) == 0:
slice_target = slice_target
if len(slice_) == 1:
stop, = slice_
slice_target = slice_target[stop]
if len(slice_) == 2:
start, stop = slice_
slice_target = slice_target[start:stop]
if len(slice_) == 3:
start, stop, step = slice_
slice_target = slice_target[start:stop:step]
return slice_target
我可以这样建议:
def slice_function(list_to_slice, slice_definition: list[int]):
try:
start = slice_definition[0]
except IndexError:
return list_to_slice
try:
stop = slice_definition[1]
except IndexError:
stop = slice_definition[0]+1
try:
step = slice_definition[2]
except IndexError:
step = 1
return list_to_slice[start:stop:step]
print(slice_function([1,4,5,6,6,76,6], [1,2,1]))
print(slice_function([1,4,5,6,6,76,6], [1,10,2]))
print(slice_function([1,4,5,6,6,76,6], [3,5]))
print(slice_function([1,4,5,6,6,76,6], [1]))
print(slice_function([1,4,5,6,6,76,6], []))
我似乎不能比这更短了:
def slice_function(slice_target, slice_: list[int]):
if len(slice_) == 0:
return slice_target
if len(slice_) == 1:
return slice_target[slice_[0]]
return slice_target[slice(*slice_)]
我的函数使用列表作为切片的索引
slice_ = [1, 2, 0] # start, stop, step
my_list = ["a", "b", "c", "d", "e", "f"]
我想写出更优雅的代码
def slice_function(slice_target, slice_: list[int]):
if len(slice_) == 0:
slice_target = slice_target
if len(slice_) == 1:
stop, = slice_
slice_target = slice_target[stop]
if len(slice_) == 2:
start, stop = slice_
slice_target = slice_target[start:stop]
if len(slice_) == 3:
start, stop, step = slice_
slice_target = slice_target[start:stop:step]
return slice_target
我可以这样建议:
def slice_function(list_to_slice, slice_definition: list[int]):
try:
start = slice_definition[0]
except IndexError:
return list_to_slice
try:
stop = slice_definition[1]
except IndexError:
stop = slice_definition[0]+1
try:
step = slice_definition[2]
except IndexError:
step = 1
return list_to_slice[start:stop:step]
print(slice_function([1,4,5,6,6,76,6], [1,2,1]))
print(slice_function([1,4,5,6,6,76,6], [1,10,2]))
print(slice_function([1,4,5,6,6,76,6], [3,5]))
print(slice_function([1,4,5,6,6,76,6], [1]))
print(slice_function([1,4,5,6,6,76,6], []))
我似乎不能比这更短了:
def slice_function(slice_target, slice_: list[int]):
if len(slice_) == 0:
return slice_target
if len(slice_) == 1:
return slice_target[slice_[0]]
return slice_target[slice(*slice_)]