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 islice(numbers, start, stop, stepquep), we extract the qujence [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 - 使用切片取得最後K個列表項目的總和的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

Uvicorn是如何持續監聽HTTP請求的? Uvicorn是一個基於ASGI的輕量級Web服務器,其核心功能之一便是監聽HTTP請求並進�...

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...
