Python 在列表中找到第一个偶数
Python有各种内置方法来修改和分析包含在其中的文本,以查找其中的特定元素。为了解决这个问题,将使用一些内置的函数,如next(),filter()和lambda来从列表中找到第一个偶数元素。这些应用程序包括数据过滤工具和内容过滤工具。
让我们看看如何输入程序来获得结果:
给定的列表:
List_1 = [21, 33, 12, 11, 61, 78]
最终结果是12,因为它是列表中的第一个偶数。
语法
在下面的示例中使用了以下语法:
next()
next()是一个内置函数,用于迭代器中的下一个项目。
filter()
filter()方法是当我们需要根据特定条件筛选项目时应用的。简单来说,它允许用户迭代那些满足条件的筛选出来的元素。
lambda
此Python中的lambda函数被称为匿名函数。当需要函数对象时,可以使用它。
使用next()函数
程序使用next()函数逐个迭代列表中的每个项。
示例
在以下示例中,通过使用一个名为even_num_first的递归函数启动程序,该函数接受名为lst的参数。通过使用函数的返回语句,它将使用内置方法next()来查找列表中的第一个偶数。next函数从迭代器中返回下一个项。在本例中,迭代器是一个仅迭代偶数的生成器表达式。如果在列表中找不到偶数,则next函数返回其第二个参数指定的-1。最后,它将使用调用函数来传递列表值。
def even_num_first(lst):
return next((i for i in lst if i%2==0),-1)
print("First even number from the following list:",even_num_first([5, 32, 4, 7, 3, 2]))
输出
First even number from the following list:
32
使用递归
该程序使用递归技术来传递所有将用于for循环和条件表达式中的参数,以解决列表中的偶数。
示例
在下面的示例中,使用名为first_even的函数作为程序的起点,接受参数- list_data以通过函数调用获取值。然后使用for循环,其中变量i遍历变量list_data中的每个值。接下来,在for循环下使用if语句来检查基于列表中的第一个偶数的条件,使用>和%运算符。最后,打印结果。
def first_even(list_data):
for i in list_data:
if i > 0 and i % 2 == 0:
return i
else:
return -1
print("The first even number from the list:",first_even([53, 81, 30, 2, 45, 76, 21]))
输出
The first even number from the list: 30
使用filter()和lambda函数
该程序使用内置方法filter()从列表中删除那些非第一个偶数。
示例
在下面的示例中,程序首先通过将整数列表初始化到变量1 num_lst 中,并使用内置函数 str() 打印列表。程序使用内置函数filter(),其中有两个参数- lambda(使用模运算符(%)检查数字是否为偶数)和num_list(给定输入列表),所有这些过程都存储在变量result中。最后,使用内置函数str()并传递参数 ‘result’ 来获取输出。
# Initializing list
num_lst = [73, 67, 71, 83, 10]
# printing original list
print("The given list : " + str(num_lst))
# Using the filter function
result = list(filter(lambda x: (x % 2 == 0), num_lst))
# print the output
print ("The first even integer from the list: " + str(result))
输出
The given list : [73, 67, 71, 83, 10]
The first even integer from the list: [10]
使用for循环
程序使用for循环来迭代列表中的每个个体元素,并使用条件表达式即if来设置第一个偶数的条件。
示例
在下面的示例中,可以使用Python程序中定义的函数来查找整数列表中的第一个偶数。该函数通过循环遍历列表,检查每个整数是否为偶数。如果发现偶数,则返回该偶数。如果未找到偶数,则返回None。然后程序调用该函数并打印结果。
def even_num_first(numbers):
for number in numbers:
if number % 2 == 0:
return number
return None
int_list = [35, 30, 11, 4, 17]
result = even_num_first(int_list)
if result is not None:
print(f"The first even number is present in the list {result}.")
else:
print("The first even number not present.")
输出
The first even number is present in the list 30.
结论
我们学习了各种内置方法,以帮助解决这个问题陈述。这种类型的程序有助于识别数据中的趋势或模式,并组织销售跟踪。通过使用上述所有示例,它还可以解决基于第一个奇数列表的类似问题。