Python如何使用列表中的备用范围切片?

2021年3月19日13:08:56 发表评论 681 次浏览

列表切片是Python中非常普遍的工具, 可以轻松地从列表中切片某些元素, 但是有时, 我们需要以非连续的方式执行该任务并切片备用范围。让我们讨论如何解决这个特殊问题。

方法1:使用列表理解

列表理解可轻松执行此特定任务, 因为它可用于运行循环并仅过滤保留剩余部分超过目标切片大小一半的元素

乘以2

。通过这种方式, 我们可以交替提取范围内的切片数。

# Python3 code to demonstrate
# alternate range slicing 
# using list comprehension
  
# initializing list 
test_list = [ 2 , 4 , 6 , 8 , 9 , 10 , 12 , 16 , 18 , 20 , 7 , 30 ]
  
# printing original list
print ( "The original list : " + str (test_list))
  
# Select range size 
N = 3
  
# using list comprehension
# alternate range slicing
res = [test_list[i] for i in range ( len (test_list)) 
                               if i % (N * 2 ) > = N]
  
# print result
print ( "The alternate range sliced list : " + str (res))

输出:

The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]

方法2:使用

enumerate()

+列表理解

列表理解也可以与枚举功能结合起来执行此任务。使用枚举的好处是我们可以跟踪索引和值, 并且比上面的函数更有效并且运行时间更少。

# Python3 code to demonstrate
# alternate range slicing 
# using list comprehension + enumerate()
  
# initializing list 
test_list = [ 2 , 4 , 6 , 8 , 9 , 10 , 12 , 16 , 18 , 20 , 7 , 30 ]
  
# printing original list
print ( "The original list : " + str (test_list))
  
# Select range size 
N = 3
  
# using list comprehension + enumerate()
# alternate range slicing
res = [val for i, val in enumerate (test_list)
                          if i % (N * 2 ) > = N]
  
# print result
print ( "The alternate range sliced list : " + str (res))

输出:

The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]

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


木子山

发表评论

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