我想从 (a_list) 列表的给定索引 (idx) 中获取 (c=3) 个元素。
输入:
a_list = [1,2,3,4,5,6,7,8,9,10]
idx = 4
c = 3 # no of neighbours to take
输出:
[2,3,4,6,7,8]
解决方案 1:通过单独的循环附加前向和后向元素。
def get_result(a_list, idx, c):
for i in range(1,c+1):
result.append(a_list[idx - i])
for i in range(1,c+1):
result.append(a_list[idx + i])
return result
解决方案 2:使用一个 for 循环和合并为前向和后向元素创建两个单独的列表。
def get_result(a_list, idx, c):
forward_list, backward_list = [],[]
for i in range(1,c+1):
forward_list.append(a_list[idx - i])
backward_list.append(a_list[idx + i])
result = [forward_list, backward_list]
return result
最佳答案
最好使用切片而不是使用循环来手动构造结果:
def get_result(a_list, idx, c):
return a_list[idx-c:idx] + a_list[idx+1:idx+c+1]
>>> get_result([1,2,3,4,5,6,7,8,9,10], 4, 3)
[2, 3, 4, 6, 7, 8]
毕竟,您的用例正是切片的用途:提取序列的连续[或至少常规]子序列。
由于 idx-c 可能结果为负,因此您可以添加一些逻辑来涵盖这种情况,例如你可以使用
a_list[max(0, idx-c):idx]
第一个被加数。
关于python - 从列表的给定索引中获取邻居数。给定解决方案的最佳实践或有效性能是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114737/