【问题标题】:Is it possible to unpack values from list to slice?是否可以将值从列表解包到切片?
【发布时间】: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

标签: python slice unpack


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      【解决方案3】:

      这不是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]
      

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

      【讨论】:

        猜你喜欢
        • 2020-10-10
        • 2015-03-18
        • 2020-12-24
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 2021-09-14
        相关资源
        最近更新 更多