【问题标题】:Working with lists and slicing使用列表和切片
【发布时间】:2015-10-20 20:20:30
【问题描述】:

这似乎是一项容易的任务,老实说,我不知道问题出在哪里。我有一个诸如 [0,1,2,3,4,5,6] 之类的列表,我需要选择和索引,比如说 3,输出应该看起来像 [4,5,6,3, 0,1,2] 这是我的代码

def cut_list(listA, index):
    return listA[index+1:] + listA[index] + listA[0:index]

然而 listA[index] 函数不能正常工作并给出错误,但是如果我取出其他部分并且只执行“return listA[index]”,它将输出 3

【问题讨论】:

  • "出现错误" -- 错误是什么?
  • return listA[index+1:] + [listA[index]] + listA[0:index]

标签: python list function


【解决方案1】:

listA[index] 是一个不能与列表连接的标量值。你正在做类似的事情:

>>> 3 + []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

列表只能与其他列表连接,因此解决方案是简单地将listA[index] 更改为一个列表,并将其作为唯一元素。例如[listA[index]]:

def cut_list(listA, index):
    return listA[index+1:] + [listA[index]] + listA[0:index]

为了使其适用于大多数序列类型,我们可以进行一些巧妙的切片:

def cut_list(listA, index):
    return listA[index+1:] + listA[index:index+1] + listA[0:index]

这是可行的,因为切片 x[idx:idx+1]应该返回与 x 相同类型的序列,该序列仅包含来自 xidx'th 元素。

>>> cut_list(range(10), 3)
[4, 5, 6, 7, 8, 9, 3, 0, 1, 2]
>>> cut_list('foo3bar', 3)
'bar3foo'
>>> cut_list(tuple(range(10)), 3)
(4, 5, 6, 7, 8, 9, 3, 0, 1, 2)

【讨论】:

  • 这可以工作,但我忘了提到的是它也必须只适用于字符串,如果我使用 () 而不是 [],它适用于字符串但不适用于列表,反之亦然
  • @HelloMellow -- 我已经更新了一个适用于大多数序列类型的解决方案。
  • 它有效,谢谢!但是为什么执行 listA[index:index+1] 不会导致,在这种情况下,第 3 个(作为 index=3)和第 4 个(index+1=3+1=4)项被打印出来?
  • @HelloMellow -- 切片返回(但不包括)最终索引。所以,lst[idx:idx] 总是会给你一个空列表。这与上一学期需要listA[0:index] 而不是listA[0:index-1] 的原因相同。
  • 另外请注意,我们可以使用listA[:index] 而不是listA[0:index] -- 他们做同样的事情。
猜你喜欢
  • 2010-12-14
  • 2017-01-01
  • 2017-07-27
  • 2014-11-02
  • 2020-05-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多