Python List倒置:b = a[::-1]的解释

本文深入解析Python中的切片操作,包括基本语法、步长参数的影响以及倒序操作。通过实例演示,帮助读者理解如何利用切片进行高效的数据处理。

在做Leetcode的题时发现,b = a[::-1]表示的是对a倒置,就像a.reverse一样。

Python基础不牢,导致无法理解为什么这样就能导致,网上找到的解释是:

链接:https://www.cnblogs.com/mxh1099/p/5804064.html

这个是python的slice notation的特殊用法。

a = [0,1,2,3,4,5,6,7,8,9]
b = a[i:j] 表示复制a[i]到a[j-1],以生成新的list对象
b = a[1:3] 那么,b的内容是 [1,2]
当i缺省时,默认为0,即 a[:3]相当于 a[0:3]
当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10]
当i,j都缺省时,a[:]就相当于完整复制一份a了

b = a[i:j:s]这种格式呢,i,j与上面的一样,但s表示步进,缺省为1.
所以a[i:j:1]相当于a[i:j]
当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1
所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍。所以你看到一个倒序的东东。

下面进行验证:

>>> a = [0,1,2,3,4,5,6,7,8]
>>> a[0]
0
>>> a[-1]
8
>>> a[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7]
>>> a[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[0:]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[:4]
[0, 1, 2, 3]
>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8]

上面这些实验说明了a[i:j]的含义,这也比较简单。

接下来对a[i:j:k]进行实验,先令k>0:

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:8:1]
[1, 2, 3, 4, 5, 6, 7]
>>> a[1:8:2]
[1, 3, 5, 7]
>>> a[1:8:3]
[1, 4, 7]
>>> a[::3]
[0, 3, 6]
>>> a[0:9:3]
[0, 3, 6]

可以看到,当k>0时,只是采样间隔从之前的挨着采变成了每隔(k-1)个采一次。事实上当k=1时,k-1=0,故对k=1时仍成立。

可见,当k>0时,a[i,j,k]表示从a[i]开始(含a[i]),到a[j]结束(不含a[j]),且顺序是从前向后进行遍历,返回遍历结果。

因此,结论是当k>0时,两个采样点之间的距离为k,按标号范围从进行采样。返回值即为采样结果。且包含a[i]但不含a[j].

 

接下来对a[i,j,k]中k=0的情况进行实验:

>>> a[1:8:0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: slice step cannot be zero

非常nice,不能为0.

 

最后,对a[i,j,k]中k<0的情况进行实验:

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:7:-1]
[]
>>> a[7:1:-1]
[7, 6, 5, 4, 3, 2]
>>> a[7:1:-2]
[7, 5, 3]
>>> a[:1:-1]
[8, 7, 6, 5, 4, 3, 2]
>>> a[7::-1]
[7, 6, 5, 4, 3, 2, 1, 0]

可见,当k<0时,a[i,j,k]表示从a[i]开始(含a[i]),到a[j]结束(不含a[j]),且顺序是从后向前进行遍历,返回遍历结果。

对比可知:

可见,当k>0时,a[i,j,k]表示从a[i]开始(含a[i]),到a[j]结束(不含a[j]),且顺序是从前向后进行遍历,返回遍历结果。

因此,其实k与i和j是无关的,k的正负值的改变只是改变了遍历的方向而已。

当k<-1时,也只是影响了遍历的间隔。

 

总结

对于需要遍历/上采样/下采样/倒置的操作而言,使用a[i,j,k应该会]非常方便。

# Copyright (c) Microsoft Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Union from playwright._impl._errors import Error from playwright._impl._map import Map API_ATTR = "_pw_api_instance_" IMPL_ATTR = "_pw_impl_instance_" class ImplWrapper: def __init__(self, impl_obj: Any) -> None: self._impl_obj = impl_obj def __repr__(self) -> str: return self._impl_obj.__repr__() class ImplToApiMapping: def __init__(self) -> None: self._mapping: Dict[type, type] = {} def register(self, impl_class: type, api_class: type) -> None: self._mapping[impl_class] = api_class def from_maybe_impl( self, obj: Any, visited: Optional[Map[Any, Union[List, Dict]]] = None ) -> Any: # Python does share default arguments between calls, so we need to # create a new map if it is not provided. if not visited: visited = Map() if not obj: return obj if isinstance(obj, dict): if obj in visited: return visited[obj] o: Dict = {} visited[obj] = o for name, value in obj.items(): o[name] = self.from_maybe_impl(value, visited) return o if isinstance(obj, list): if obj in visited: return visited[obj] a: List = [] visited[obj] = a for item in obj: a.append(self.from_maybe_impl(item, visited)) return a api_class = self._mapping.get(type(obj)) if api_class: api_instance = getattr(obj, API_ATTR, None) if not api_instance: api_instance = api_class(obj) setattr(obj, API_ATTR, api_instance) return api_instance else: return obj def from_impl(self, obj: Any) -> Any: assert obj result = self.from_maybe_impl(obj) assert result return result def from_impl_nullable(self, obj: Any = None) -> Optional[Any]: return self.from_impl(obj) if obj else None def from_impl_list(self, items: Sequence[Any]) -> List[Any]: return list(map(lambda a: self.from_impl(a), items)) def from_impl_dict(self, map: Dict[str, Any]) -> Dict[str, Any]: return {name: self.from_impl(value) for name, value in map.items()} def to_impl( self, obj: Any, visited: Optional[Map[Any, Union[List, Dict]]] = None ) -> Any: if visited is None: visited = Map() try: if not obj: return obj if isinstance(obj, dict): if obj in visited: return visited[obj] o: Dict = {} visited[obj] = o for name, value in obj.items(): o[name] = self.to_impl(value, visited) return o if isinstance(obj, list): if obj in visited: return visited[obj] a: List = [] visited[obj] = a for item in obj: a.append(self.to_impl(item, visited)) return a if isinstance(obj, ImplWrapper): return obj._impl_obj return obj except RecursionError: raise Error("Maximum argument depth exceeded") def wrap_handler(self, handler: Callable[..., Any]) -> Callable[..., None]: def wrapper_func(*args: Any) -> Any: arg_count = len(inspect.signature(handler).parameters) return handler( *list(map(lambda a: self.from_maybe_impl(a), args))[:arg_count] ) if inspect.ismethod(handler): wrapper = getattr(handler.__self__, IMPL_ATTR + handler.__name__, None) if not wrapper: wrapper = wrapper_func setattr( handler.__self__, IMPL_ATTR + handler.__name__, wrapper, ) return wrapper wrapper = getattr(handler, IMPL_ATTR, None) if not wrapper: wrapper = wrapper_func setattr(handler, IMPL_ATTR, wrapper) return wrapper 分析这段代码,让我能看懂
06-05
Python中的DataFrame倒置可以通过使用transpose()函数来实现。该函数可以将DataFrame的行和列进行交换。具体操作如下所示: 1. 首先,导入pandas库:import pandas as pd 2. 创建一个DataFrame对象,可以使用pd.DataFrame()函数,并指定数据、行索引和列索引:data = pd.DataFrame(data, index, columns) 3. 接下来,使用transpose()函数对DataFrame进行倒置操作:data_transposed = data.transpose() 通过上述步骤,你可以实现Python中DataFrame的倒置操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [读取json文件为dataframe后行列倒置的解决办法,以及dataframe基本操作(删除指定行、列,根据值筛选等)](https://blog.csdn.net/weixin_39417324/article/details/120555744)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [pandas之DataFrame的创建、属性、索引设置和转置](https://blog.csdn.net/qq_42596359/article/details/106941842)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NLOS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值