搜尋
首頁後端開發Python教學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 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中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
如何解決Linux終端中查看Python版本時遇到的權限問題?如何解決Linux終端中查看Python版本時遇到的權限問題?Apr 01, 2025 pm 05:09 PM

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

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?Apr 01, 2025 pm 11:15 PM

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

哪些流行的Python庫及其用途?哪些流行的Python庫及其用途?Mar 21, 2025 pm 06:46 PM

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

如何使用Python創建命令行接口(CLI)?如何使用Python創建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

解釋Python中虛擬環境的目的。解釋Python中虛擬環境的目的。Mar 19, 2025 pm 02:27 PM

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。

什麼是正則表達式?什麼是正則表達式?Mar 20, 2025 pm 06:25 PM

正則表達式是在編程中進行模式匹配和文本操作的強大工具,從而提高了各種應用程序的文本處理效率。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境