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 方法使用各种功能在计算前缀和后打印列表。

更新于:2023年9月4日

68 次浏览

启动你的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.