是否可以将值从列表解包到切片?

Eth*_*thr 1 python unpack slice

我正在尝试使用列表中的值来选择单词的一部分。这是工作解决方案:

word = 'abc'*4
slice = [2,5]  #it can contain 1-3 elements

def try_catch(list, index):
    try:
        return list[index]
    except IndexError:
        return None

print(word[slice[0]:try_catch(slice,1):try_catch(slice,2)])
Run Code Online (Sandbox Code Playgroud)

但我想知道是否可以缩短它?我想到了这样的事情:

word = 'abc'*4
slice = [2,6,2]
print(word[':'.join([str(x) for x in slice])]) #missing : for one element in list
Run Code Online (Sandbox Code Playgroud)

它产生:

TypeError: string indices must be integers
Run Code Online (Sandbox Code Playgroud)

mkr*_*er1 5

您可以使用内置slice(并且需要以不同的方式命名您的列表才能访问内置):

>>> word = 'abcdefghijk'
>>> theslice = [2, 10, 3]
>>> word[slice(*theslice)]
'cfi'
Run Code Online (Sandbox Code Playgroud)