Python – 交替后向迭代


简介

使用 Python 实现交替后向迭代涉及列表数据结构和功能的基本用法,并借助循环结构。此问题应用简单的数学技能,使我们能够确定偶数以打印从后侧开始的交替数字。Python 语言中提供的数据结构包括列表、元组和字典。它为用户提供了遍历不同类型数据结构的功能。最常见的是,for 循环用于遍历列表或元组。

交替后向迭代

在本文中,迭代从给定列表的后部或尾部开始,与从前端开始迭代相比,效率更高。

方法

方法 1 - 使用 for 循环

方法 2 - 使用切片方法

方法 3 - 使用 lambda 函数

方法 1:使用 for 循环进行 Python 交替后向迭代程序

range() 函数声明了三个参数,它们是给定列表的长度作为 len(list_1)-1,表示列表的最后一个索引,第二个参数是 -1,表示迭代不应超出开头,最后一个参数是 -1,表示我们必须向后或向尾部移动。

算法

  • 步骤 1 - 使用整数元素初始化列表。

  • 步骤 2 - 初始化空列表。

  • 步骤 3 - for 循环用于从尾部迭代列表的每个元素。

  • 步骤 4 - 使用 len() 函数识别列表的长度,并使用 range() 函数维护元素的范围。

  • 步骤 5 - 然后,print 语句用于在后向迭代后返回元素列表。

示例

#initializing the list with integer elements
list_1 = [1,2,3,4,5,6,8]
#initializing the empty list
alternate_list = []
#for loop is used to iterate through the loop from the rear using the range() and len() function
for a in range(len(list_1)-1,-1,-2):
   alternate_list.append(list_1[a])
#returns the elements of the list iterated from the rear
print("Alternate rear iteration:", alternate_list)

输出

Alternate rear iteration: [8, 5, 3, 1]

方法 2:使用切片方法进行 Python 交替后向迭代程序

切片方法用于以 -1 的步长遍历字符串。遵循此方法,而不是从左到右迭代。

算法

  • 步骤 1 - 提示用户输入值,并借助 split() 函数将输入的整数拆分为单独的元素。

  • 步骤 2 - 给定的字符串只需进行切片方法即可反转给定的字符串。

  • 步骤 3 - 然后,print 语句用于返回字符串的反转字符。

示例

#The user is prompted to enter the integers with proper spaces
#split() function is used to split the given strings into separate ones
list1 = [1, 2, 3, 5, 7, 9, 4]
list1 = [int(a) for a in list1]

#The list of elements given by the user and the string is reversed using the slicing method
alternate_list = list(reversed(list1[::2]))
#printing statement will return the given input in a reversed alternate order
print("Alternate rear iteration:", alternate_list)

输出

Alternate rear iteration: [4, 7, 3, 1]

方法 3:使用 lambda 函数进行 Python 交替后向迭代程序

在函数的情况下,我们使用 def 函数,但对于匿名函数,我们可以使用 lambda 函数以及 key 参数。lambda 函数通常与 filter() 或 map() 函数一起使用。

算法

  • 步骤 1 - 提示用户输入整数,并在空格之间存储在名为 list1 的变量中。

  • 步骤 2 - 借助 split() 函数,将输入的整数拆分为单独的元素。

  • 步骤 3 - 使用列表推导式将给定的值字符串转换为整数数据类型。

  • 步骤 4 - 由于 filter 函数总是与 lambda 函数一起使用,因此它从尾部过滤给定的元素列表。

  • 步骤 5 - key 参数“m”用于检查它是否是偶数。

  • 步骤 6 - 稍后,使用 reversed() 函数反转转换后的输入字符串以进行后向迭代过程。

  • 步骤 7 - 然后,print 语句用于在后向迭代后返回元素列表。

示例

#The user is prompted to enter the integers with proper spaces
#split() function is used to split the given strings into separate ones
list1 = [1, 2, 3, 5, 7, 9, 4]
list1 = [int(a) for a in list1]

#lambda function is used to get the alternate rear iteration using filter() and map() function
alternate_list = list(filter(lambda m: list1.index(m) % 2 == 0, reversed(list1)))
#printing statement will return the given input in a reversed alternate order
print("Alternate rear iteration:", alternate_list)

输出

Alternate rear iteration: [4, 7, 3, 1]

结论

在当今世界,对于数据量庞大的组织来说,处理数据是最具挑战性的任务,随着数据科学和机器学习的发展,访问数据变得更加容易。Python 是一种用途广泛的高级语言,用户可以轻松理解。

更新于: 2023年8月25日

206 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.