python 倒序取后两项
时间: 2023-11-15 08:00:36 浏览: 35
可以使用Python的切片(slice)操作来实现倒序取后两项。具体方法如下:
```python
my_list = [1, 2, 3, 4, 5]
last_two_items = my_list[-2:]
print(last_two_items)
```
输出结果为:
```
[4, 5]
```
其中,`my_list[-2:]` 表示从列表 `my_list` 的倒数第二个元素开始(包括该元素),一直到列表末尾的所有元素,即倒序取后两项。
相关问题
Python倒序遍历
Python中可以使用内置函数`reversed()`对一个序列进行倒序遍历,这个函数返回一个反向迭代器对象。使用方法如下:
```
my_list = [1, 2, 3, 4, 5]
for i in reversed(my_list):
print(i)
```
这段代码会输出:5 4 3 2 1
另外,也可以使用切片操作对序列进行倒序排列:
```
my_list = [1, 2, 3, 4, 5]
for i in my_list[::-1]:
print(i)
```
这段代码也会输出:5 4 3 2 1
python 倒序读取excel
以下是使用Python倒序读取Excel的方法:
```python
import pandas as pd
# 读取Excel文件
df = pd.read_excel('your_excel_file.xlsx')
# 倒序读取Excel文件
df_reverse = df.iloc[::-1]
# 输出倒序后的结果
print(df_reverse)
```
其中,`pd.read_excel()`函数用于读取Excel文件,`iloc[::-1]`用于将DataFrame倒序排列。如果需要倒序排列某一列,可以使用以下代码:
```python
import pandas as pd
# 读取Excel文件
df = pd.read_excel('your_excel_file.xlsx')
# 倒序排列某一列
df_reverse = df.sort_values(by='your_column_name', ascending=False)
# 输出倒序后的结果
print(df_reverse)
```
其中,`sort_values()`函数用于按照指定列排序,`ascending=False`表示降序排列。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)