0

0

Python - 使用切片获取最后K个列表项的总和

WBOY

WBOY

发布时间:2023-09-06 11:17:06

|

1831人浏览过

|

来源于tutorialspoint

转载

python - 使用切片获取最后k个列表项的总和

在Python中,切片方法允许我们从序列(如字符串、列表或元组)中提取特定元素。它提供了一种简洁灵活的方式来处理较大序列中的子序列。在本文中,我们将探讨如何使用切片操作获取列表中最后K个元素的和。

算法

To find the sum of the last K items in a list, we can follow a simple algorithm:

  • 接受列表和K的值作为输入。

  • 使用切片操作符从列表中提取最后K个项目。

    立即学习Python免费学习笔记(深入)”;

  • 计算提取项目的总和。

  • Return the sum as the output.

语法

sequence[start:end:step]

在这里,slice方法接受三个可选参数:

  • start (optional): The index of the element where the slice should start. If not provided, it defaults to the beginning of the sequence.

  • end(可选):切片应该结束的元素的索引(不包括)。如果未提供,则默认为序列的末尾。

    ChartGen
    ChartGen

    AI快速生成专业数据图表

    下载
  • step (optional): The step or increment value for selecting elements. If not provided, it defaults to 1.

The start, end and step values can be positive or negative integers, allowing you to traverse the sequence in both forward and backward directions.

示例1:使用切片方法求最后K个项目的总和

通过在切片中指定负索引,我们可以从列表的末尾开始向后遍历。以下是使用切片获取最后K个列表项的总和的语法:

In the below example, we have a list my_list containing 10 elements. We want to find the sum of the last 4 items in the list. By using the slice operator [-K:], we specify the range from the fourth−to−last element to the end of the list. The sum() function then calculates the sum of the extracted elements, resulting in 280.

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
K = 4
sum_of_last_k = sum(my_list[-K:])
print("Sum of last", K, "items:", sum_of_last_k)

输出

Sum of last 4 items: 340

示例2:使用集合模块中的tail函数

来自collections模块的tail函数是一种方便的方法,用于从序列中提取最后N个元素。它允许您避免使用负索引进行切片。

在下面的示例中,我们从collections模块导入deque类,并将所需的最大长度(maxlen)指定为N。通过将numbers列表和maxlen=N传递给deque,我们创建一个仅保留最后N个元素的deque对象。使用list(tail_elements)将deque对象转换为列表,可以获得尾部元素[6, 7, 8, 9, 10]。

from collections import deque

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
N = 5
tail_elements = deque(numbers, maxlen=N)
print(list(tail_elements))

输出

[6, 7, 8, 9, 10]

Example 3: Using the islice function from the itertools module

The islice function from the itertools module allows you to extract a specific subsequence from an iterable, such as a list or string, by providing the start, stop, and step values.

In the below example, we import the islice function from the itertools module. By passing the numbers list along with the start, stop, and step values to islice(numbers, start, stop, step), we extract the desired subsequence [6, 8, 10]. Converting the result to a list using list(islice(...)) enables us to print the subsequence

from itertools import islice

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
start = 5
stop = 10
step = 2
subsequence = list(islice(numbers, start, stop, step))
print(subsequence)

输出

[6, 8, 10]

Conclusion

在本文中,我们讨论了如何使用切片方法来获取最后k个项目的总和。切片方法提供了一种简洁高效的方式来执行此类计算,并使得获取列表最后k个项目的总和变得容易。切片方法还可以用于其他目的,如提取子序列,跳过具有步长值的元素,反转序列,获取最后k个元素等。

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Golang gRPC 服务开发与Protobuf实战
Golang gRPC 服务开发与Protobuf实战

本专题系统讲解 Golang 在 gRPC 服务开发中的完整实践,涵盖 Protobuf 定义与代码生成、gRPC 服务端与客户端实现、流式 RPC(Unary/Server/Client/Bidirectional)、错误处理、拦截器、中间件以及与 HTTP/REST 的对接方案。通过实际案例,帮助学习者掌握 使用 Go 构建高性能、强类型、可扩展的 RPC 服务体系,适用于微服务与内部系统通信场景。

8

2026.01.15

公务员递补名单公布时间 公务员递补要求
公务员递补名单公布时间 公务员递补要求

公务员递补名单公布时间不固定,通常在面试前,由招录单位(如国家知识产权局、海关等)发布,依据是原入围考生放弃资格,会按笔试成绩从高到低递补,递补考生需按公告要求限时确认并提交材料,及时参加面试/体检等后续环节。要求核心是按招录单位公告及时响应、提交材料(确认书、资格复审材料)并准时参加面试。

44

2026.01.15

公务员调剂条件 2026调剂公告时间
公务员调剂条件 2026调剂公告时间

(一)符合拟调剂职位所要求的资格条件。 (二)公共科目笔试成绩同时达到拟调剂职位和原报考职位的合格分数线,且考试类别相同。 拟调剂职位设置了专业科目笔试条件的,专业科目笔试成绩还须同时达到合格分数线,且考试类别相同。 (三)未进入原报考职位面试人员名单。

58

2026.01.15

国考成绩查询入口 国考分数公布时间2026
国考成绩查询入口 国考分数公布时间2026

笔试成绩查询入口已开通,考生可登录国家公务员局中央机关及其直属机构2026年度考试录用公务员专题网站http://bm.scs.gov.cn/pp/gkweb/core/web/ui/business/examResult/written_result.html,查询笔试成绩和合格分数线,点击“笔试成绩查询”按钮,凭借身份证及准考证进行查询。

11

2026.01.15

Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

65

2026.01.14

php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

36

2026.01.13

PHP 高性能
PHP 高性能

本专题整合了PHP高性能相关教程大全,阅读专题下面的文章了解更多详细内容。

75

2026.01.13

MySQL数据库报错常见问题及解决方法大全
MySQL数据库报错常见问题及解决方法大全

本专题整合了MySQL数据库报错常见问题及解决方法,阅读专题下面的文章了解更多详细内容。

21

2026.01.13

PHP 文件上传
PHP 文件上传

本专题整合了PHP实现文件上传相关教程,阅读专题下面的文章了解更多详细内容。

35

2026.01.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号