问题:您有一个列表,需要从列表中高效地检索每隔三个的项目。
解决方案 1:使用 For 循环
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []
for i in range(2, len(my_list), 3):
result.append(my_list[i])
print(result) # [3, 6, 9]
解决方案 2:使用列表理解
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = [my_list[i] for i in range(2, len(my_list), 3)]
print(result) # [3, 6, 9]
解决方案 3:使用 NumPy(如果使用数组)
import numpy as np
my_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
result = my_array [2::3]
print (result.tolist()) # Convert NumPy array back to a Python list if needed
# [3, 6, 9]
