我有一组数据,我想将一些值彼此太接近的元素设置为 0。所以假设我有一个阈值T=1
.如果list[i+1] - list[i] < T*2
,它将list[i]
元素设置为 0。我编写了一些代码,如下所示:
a = [9, 39, 46, 76, 84, 114, 122, 150, 151, 152, 155, 198, 210]
T=1
def sort (item):
for i in range(len(item)):
if item[i] - item[i+1] < 2*T:
item[i+1] == 0
return item
print (sort(a))
但是,当我运行此代码时,它给了我一个错误:
IndexError: list index out of range.
我想要的输出是:
a = [9, 39, 46, 76, 84, 114, 122, 0, 0, 0, 155, 198, 210]
正如您在上面看到的,它将 150,151,152 设置为 0。如果有人知道如何解决这个问题,请告诉我。赞赏!!
a = [9, 9, 46, 76, 84, 114, 122, 150, 151, 152, 155, 198, 199]
T=1
def make_zero(arr, T):
index_values = []
for i in range(0, len(arr)):
if i == 0:
if abs(arr[i] - arr[i+1]) < 2*T:
index_values.append(i)
elif i == len(arr):
if abs(arr[i] - arr[i-1]) < 2*T:
index_values.append(i)
elif abs(arr[i] - arr[i-1]) < 2*T:
index_values.append(i)
elif abs(arr[i] - arr[i+1]) < 2*T:
index_values.append(i)
for j in index_values:
arr[j] = 0
return arr
output = make_zero(a,T)
print output
现在根据您的更新,我得出了一个带有一些幼稚方法的解决方案:
def set_neighbours_to_zero(input, threshold=1):
# calculate the distance between the list items
distance = {(input[i], input[i+1]): input[i+1] - input[i]
for i in range(len(input) - 1) if i < len(input) - 1}
# get all too close neighbours
nullable = set()
for k,v in distance.items():
if v < 2 * threshold:
nullable.update(k)
# in the last step set the close neighbours to zero
for n in nullable:
index = input.index(n)
input[index] = 0
# return the modified list
return input
如果运行该函数,它应返回以下内容:
a = [9, 39, 46, 76, 84, 114, 122, 150, 151, 152, 155, 198, 210]
print(set_neighbours_to_zero(a))
>>> [9, 39, 46, 76, 84, 114, 122, 0, 0, 0, 155, 198, 210]
我的方法是获取列表中所有相邻数字之间的距离。稍后我们可以将所有距离小于阈值的邻里小时设置为零。此方法假定输入列表始终按升序排序,并且其元素为整数。
它看起来有点笨拙,但我希望你能改进它。
编辑:
这部分可以缩短:
# calculate the distance between the list items
distance = {(input[i], input[i+1]): input[i+1] - input[i]
for i in range(len(input) - 2)}
我们想要得到一个数字与其连续邻域之间的距离。由于列表中的最后一个数字没有连续的邻居,我们可以从第一个数字迭代到第二个数字到最后一个数字。这是一个字典理解,并将元组作为键返回,距离作为值。例:
{
(9, 39): 30,
(39, 46): 7,
...
}