Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何使用其索引反转或迭代列表?
这是一个例子
lst = [3,2,4,1,5]
输出将是:([3,2,4,5,1]最后是 1 的索引 3)
[3,2,4,5,1]
另一个例子:
lst = [1,5,4,2,3]
输出:([1,5,4,3,2]索引 3 即 2 放在最后)
[1,5,4,3,2]
就像使用切片反转列表一样。
如果您想将列表的一部分反转过去某个点,最直接的方法是:
output = (lst[:3] # take the list before element 3 + # and add lst[3:] # the list from element 3 on [::-1] # reversed )
或者,没有评论:
output = lst[:3] + lst[3:][::-1]
如果要更改现有列表,您可以:
lst[3:] = lst[3:][::-1]