[英]Delete elements in list that are closer than N from each other
Let's suppose I have the following list:假设我有以下列表:
a = [0,5,10,11,15,22]
...and I want to make sure that the list elements are always a minimum of 5 apart from each other, how could I do that? ...而且我想确保列表元素之间的距离始终至少为 5,我该怎么做?
expected result:预期结果:
[0,5,10,15,22]
What I tried is not very pythonic:我尝试的不是很pythonic:
a.sort()
prev_elem = a[0]
new_list = []
for elem in a[1:]:
if abs(prev_elem-elem) >= 5:
new_list.append(prev_elem)
# update
prev_elem = elem
EDIT: BEFORE YOU DOWNVOTE : Why are you downvoting?编辑:在你投反对票之前:你为什么投反对票? Please add a comment?
请添加评论? I am asking a question and I have shown my work, so there is no reason to downvote.
我在问一个问题并且我已经展示了我的作品,所以没有理由拒绝投票。
You can do it with a few very small changes to your existing code.您可以通过对现有代码进行一些非常小的更改来实现。
Lines that are changed are commented below.更改的行在下面注释。
a = [0,5,10,11,15,22]
a.sort()
prev_elem = a[0]
new_list = [prev_elem] # <====== initialise with one element
for elem in a[1:]:
if abs(prev_elem-elem) >= 5:
new_list.append(elem) # <===== append the new element
prev_elem = elem # <===== indented more (inside "if" block)
print(new_list)
This gives:这给出:
[0, 5, 10, 15, 22]
Iterate through the list.遍历列表。 If arr[i]+5 >arr[i+1], then delete arr[i+1].
如果 arr[i]+5 > arr[i+1],则删除 arr[i+1]。 Something like the following code.
类似于以下代码。
i = 0
while i < len(arr)-1:
if arr[i]+5 > arr[i+1]:
del arr[i+1]
else:
i+=1
There's definitely cleaner and more efficient ways to do this, but this should work.肯定有更清洁、更有效的方法来做到这一点,但这应该有效。
Note this is pseudo code where n is the length of the array named arr:请注意,这是伪代码,其中 n 是名为 arr 的数组的长度:
for i = 1 to n
if (arr[i] - arr[i - 1] >= 5 OR arr[i] - arr[i - 1] <= -5)
//remove arr[i]
One way of doing it:一种方法:
a = [0,5,10,11,15,22]
result = []
for i, num in enumerate(a):
if i == 0:
result.append(num)
continue
if 3 <= abs(num - a[i-1]):
result.append(num)
# [0,5,10,11,15,22] -> [0, 5, 10, 15, 22]
# [10, 9, 5, 0] -> [10, 5, 0]
# [10, 14, 9, 11, 5, 7, 0] -> [10, 14, 9, 5, 0]
EDIT:编辑:
I realized that it can be done simpler.我意识到它可以做得更简单。 Using slice and unpacking avoids index error in case of empty list:
使用切片和解包避免在空列表的情况下出现索引错误:
result = [*a[0:1]]
for num in a[1:]:
if 3 <= abs(num - result[-1]):
result.append(num)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.