【发布时间】:2019-06-09 17:12:51
【问题描述】:
我正在尝试使用列表中的值来选择单词的一部分。这是可行的解决方案:
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,因为它会覆盖__builtin__.slice。您可能正在寻找word[slice(*[2,6,2])](在此处使用内置函数,而不是您的变量),但如果没有所需的输出就很难分辨。在此处阅读更多信息What does the slice() function do?。 -
那么你想构建下面的切片
2:6:2? -
您的“工作解决方案”错误并带有
SyntaxError。 -
word[start:stop:step]在slice = [2,6,2]的情况下是word[2:6:2]所以只是cb