Python – 直到出現False值的子陣列字首和
Python 程式設計是一種用途廣泛的程式語言,易於用作高階語言。它降低了處理海量資料時複雜操作的難度。陣列是一種儲存元素的資料結構,子陣列是存在於陣列結構內部的陣列。陣列可以儲存相同資料型別的元素,並以方形格式排序。陣列中元素的大小也相同。
Python – 直到出現False值的子陣列字首和
在 Python 語言中,變數被賦值以儲存資料,但陣列可以一次按指定順序儲存更多的資料。在本文中,我們將處理元素直到條件失敗。最好的方法是透過示例來理解:
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
1 |
4 |
8 |
0 |
10 |
5 |
2 |
1 |
陣列中的每個元素都由其索引值標識,並且在這種情況下保留第一個元素。將第一個和第二個元素相加並存儲在索引值 1 中。將第二個和第三個元素相加並存儲在索引值 2 中。當陣列中的元素為 0 時,它將結果返回為 0,並且此過程繼續。
方法
方法 1 - 使用 try 和 except 方法
方法 2 - 使用迭代方法
方法 1:使用 try 和 except 方法列印直到出現 False 值的子陣列字首和的 Python 程式
列印初始化的子陣列直到出現 False 值的字首和的程式涉及 try 和 except 方法。一些 False 值是 0、False、[]、{}、0.0 等等。
演算法
步驟 1 - 列表用整數資料型別初始化。
步驟 2 - 定義空列表,然後將一個變數儲存為 0。
步驟 3 - 使用 try 和 except 方法迭代列表的每個元素。
步驟 4 - 當條件為假(為零)時,迴圈中斷。
步驟 5 - 使用 append 函式新增元素。
步驟 6 - print 函式返回最終列表。
示例
#initializing the list data structure
list1 = [2, 10, 4, 3, 0.0, 10, -2]
#empty list is initialized
arr = []
#the variable is declared as 0
num = 0
# Use the try and except method to print the sum until a false value occurs
try:
#for loop is used to iterate through the list
for val in list1:
#To check whether the value is a false element
if val == False:
break
#When it is not a false element, then the values are added using the append function
num += val
arr.append(num)
#the print function returns the list
print ("The array after product sum : " + str(arr))
except:
#When the false element is something like an empty list or strings it returns an error
print("An error occurred")
輸出
The array after product sum : [2, 12, 16, 19]
方法 2:使用迭代方法列印直到出現 False 值的子陣列字首和的 Python 程式
列表中的元素進行字首和運算,直到出現 False 值。為此,使用 for 迴圈迭代列表的每個元素。
演算法
步驟 1 - 列表用整數和一個 False 元素(如 0)初始化。
步驟 2 - 初始化空列表,併為名為“num”的新變數賦值為‘0’
步驟 3 - for 迴圈用於遍歷元素列表。
步驟 4 - 當條件為假(為零)時,迴圈中斷。
步驟 5 - 當結果不是 False 時,它將 num 新增到 arr 中。
步驟 6 - 使用 append 函式新增元素。
步驟 7 - print 函式將返回最終列表。
示例
#initializing the list with elements
list1 = [2, 10, 4, 3, 0, 10, -2]
#defining the empty list
arr = []
num = 0
#iteration through the list
for val in list1:
if val == False:
break
num += val
arr.append(num)
# It converts the list array to a string and [:] will create a copy of the list
print ("The array after prefix sum : " + str(arr[:]))
輸出
The array after prefix sum : [2, 12, 16, 19]
結論
Python 語言為使用者提供了從基本計算到複雜計算的各種功能。當我們說列印直到 False 值的字首和似乎是一個簡單的任務時,但在建立程式時,會涉及一些繁瑣的過程。Python 方法使用各種功能在計算字首和後列印列表。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP