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

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

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

``````# 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]``````

+列表理解

``````# 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]``````