Python |包含所有替代元素的列表用法详解

2021年3月16日11:58:31 发表评论 609 次浏览

其中一些列表操作相当笼统, 并且总是需要简写而不需要编写多行代码。想要构造由原始列表的所有替代元素组成的列表是一个开发人员在日常应用程序中面临的问题。

让我们讨论一些打印给定列表的所有替代元素的方法。

方法1:使用列表理解

列表理解是朴素方法的简写, 它提供了一种执行此特定任务的更快方法。在此方法中, 不是2的倍数的所有索引, 因此是奇数, 将插入新列表中。

# Python code to demonstrate 
# to construct alternate element list
# using list comprehension 
  
# initializing list 
test_list = [ 1 , 4 , 6 , 7 , 9 , 3 , 5 ]
  
# printing original list 
print ( "The original list : " + str (test_list))
  
# using list comprehension
# to construct alternate element list
res = [test_list[i] for i in range ( len (test_list)) if i % 2 ! = 0 ]
  
# printing result 
print ( "The alternate element list is : " + str (res))

输出如下:

The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]

方法2:使用enumerate()

这只是列表理解方法的一种变体, 但内部工作与列表理解类似, 但是使用不同的变量来跟踪索引及其值。

# Python code to demonstrate 
# to construct alternate element list
# using enumerate() 
  
# initializing list 
test_list = [ 1 , 4 , 6 , 7 , 9 , 3 , 5 ]
  
# printing original list 
print ( "The original list : " + str (test_list))
  
# using enumerate()
# to construct alternate element list
res = [i for j, i in enumerate (test_list) if j % 2 ! = 0 ]
  
# printing result 
print ( "The alternate element list is : " + str (res))

输出如下:

The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]

方法3:使用切片符号

这是执行此特定任务的最pythonic且优雅的方法, 并增强了python的全部功能。我们可以使用slice提供的skip实用程序来获取列表中从头到尾的备用元素。

# Python code to demonstrate 
# to construct alternate element list
# using Slice notation
  
# initializing list 
test_list = [ 1 , 4 , 6 , 7 , 9 , 3 , 5 ]
  
# printing original list 
print ( "The original list : " + str (test_list))
  
# using Slice notation
# to construct alternate element list
res = test_list[ 1 :: 2 ]
  
# printing result 
print ( "The alternate element list is : " + str (res))

输出如下:

The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: