Erb*_*yev 4 python items list distance python-3.x
我只需要获得在某种程度上彼此远离的元素/项目.例如,我有一个整数列表:
data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]
Run Code Online (Sandbox Code Playgroud)
让我们假设我只想检索那些彼此之间的距离至少为1000的元素.从上面的列表我需要输出:
[-2000, 1000, 2000, 3500, 4500, 6000]
Run Code Online (Sandbox Code Playgroud)
我这样过滤:
filtered.append(data[0])
for index, obj in enumerate(data):
if index < (l - 1):
if abs(obj - data[index+1]) > 999:
filtered.append(data[index+1])
print(filtered)
Run Code Online (Sandbox Code Playgroud)
不受欢迎的输出:
[-2000, 1000, 2000, 3500, 6000]
Run Code Online (Sandbox Code Playgroud)
它失败了,因为它比较了两个相邻的列表元素,而不管一些元素应该被过滤掉而不应该被考虑在内.
让我更清楚地表明.
原始清单:[-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]
过滤过程:
-2000 - OK
1000 - OK
2000 - OK
3500 - OK
3800 - Out
4500 - Should be OK, but it filtered out compared to 3800. But it should be compared to 3500 (not 3800 which is Out).
Run Code Online (Sandbox Code Playgroud)
怎么解决?
对数据进行排序然后与之前的数据进行比较就可以了:
data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]
lst = [min(data)] # the min of data goes in solution list
for i in sorted(data[1:]):
if i-lst[-1] > 999: # comparing with last element
lst.append(i) # of the solution list
print (lst)
Run Code Online (Sandbox Code Playgroud)
输出继电器:
[-2000, 1000, 2000, 3500, 4500, 6000]
Run Code Online (Sandbox Code Playgroud)