Python - Get sum of last K list items using slicing

WBOY
Release: 2023-09-06 11:17:06
forward
1497 people have browsed it

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

In Python, the slicing method allows us to extract specific elements from a sequence such as a string, list, or tuple. It provides a concise and flexible way to handle subsequences within larger sequences. In this article, we will explore how to get the sum of the last K elements in a list using slicing operations.

algorithm

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

  • Accepts a list and the value of K as input.

  • Use the slicing operator to extract the last K items from the list.

  • Calculate the sum of extracted items.

  • Return the sum as the output.

grammar

sequence[start:end:step]
Copy after login

Here, the slice method accepts three optional parameters:

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

  • end (optional): The index (exclusive) of the element at which the slice should end. If not provided, defaults to the end of the sequence.

  • 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.

Example 1: Use the slicing method to find the sum of the last K items

By specifying negative indexes in the slice, we can traverse backward starting from the end of the list. Here is the syntax for using slicing to get the sum of the last K list items:

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)
Copy after login

Output

Sum of last 4 items: 340
Copy after login

Example 2: Using the tail function in the collection module

The tail function from the collections module is a convenience method for extracting the last N elements from a sequence. It allows you to avoid slicing with negative indices.

In the following example, we import the deque class from the collections module and specify the required maximum length (maxlen) as N. By passing the numbers list and maxlen=N to deque, we create a deque object that holds only the last N elements. Use list(tail_elements) to convert the deque object into a list, and you can get the tail elements [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))
Copy after login

Output

[6, 7, 8, 9, 10]
Copy after login

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)
Copy after login

Output

[6, 8, 10]
Copy after login

Conclusion

In this article, we discussed how to use the slicing method to get the sum of the last k items. The slicing method provides a concise and efficient way to perform such calculations and makes it easy to get the sum of the last k items of the list. The slicing method can also be used for other purposes like extracting subsequences, skipping elements with step values, reversing sequences, getting the last k elements, etc.

The above is the detailed content of Python - Get sum of last K list items using slicing. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template