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

Is it possible to unpack values from list to slice?

我正在尝试将列表中的值用于单词的 select 部分。这是有效的解决方案:

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)])

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

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

它产生:

TypeError: string indices must be integers

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

>>> word = 'abcdefghijk'
>>> theslice = [2, 10, 3]
>>> word[slice(*theslice)]
'cfi'

它不是 python [slice][1],但会导致语法错误,因为 [..] 用于获取切片而不是创建切片的语法:

slice = [2:5]
Out:
...
SyntaxError

slice 是一个 python 内置函数,所以不要隐藏它的名字。创建切片为

my_slice = slice(2, 5, 1)

其中第一个参数是起始值,下一个是停止值,最后一个是步长:

my_list = list(range(10))
my_list
Out:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

my_list[my_slice]
Out:
[2, 3, 4]

my_list[slice(3, 8, 2)]
Out:
[2, 4, 6]

请注意,我们应该将 [] 与切片一起使用,因为它调用接受 slice 个对象的列表的 __getitem__ 方法(查看最后的 link __getitem__slice).

试试这个:

word = 'abc'*4
w = list(word)
s = slice(2,6,2)
print("".join(w[s]))