卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章17904本站已运行3328

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

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

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

算法

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

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

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

  • 计算提取项目的总和。

  • 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(可选):切片应该结束的元素的索引(不包括)。如果未提供,则默认为序列的末尾。

  • 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个元素等。

卓越飞翔博客
上一篇: 在C程序中打印给定数字的个位数的倍数
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏