这不是一个花哨的单行代码,但如果当前值大于新列表中的最后一个值,您可以迭代列表中的值并将它们附加到某个新列表中,使用[-1]
:
lst = range(10)
diff = 3
new = []
for n in lst:
if not new or abs(n - new[-1]) >= diff:
new.append(n)
然后,new
is [0, 3, 6, 9]
.
关于你的评论“如果我有一个坐标列表(x,y)怎么办?”:在这种情况下,你做完全相同的事情,除了不只是比较数字,你必须找到欧氏距离 https://en.wikipedia.org/wiki/Euclidean_distance两点之间。所以,假设lst
是一个列表(x,y)
pairs:
if not new or ((n[0]-new[-1][0])**2 + (n[1]-new[-1][1])**2)**.5 >= diff:
或者,您可以将您的(x,y)
配对成complex https://docs.python.org/3.5/library/functions.html#complex数字。对于这些,加法、减法和绝对值等基本运算已经定义,因此您可以再次使用上面的代码。
lst = [complex(x,y) for x,y in lst]
new = []
for n in lst:
if not new or abs(n - new[-1]) >= diff: # same as in the first version
new.append(n)
print(new)
Now, new
是表示点的复数列表:[0j, (3+3j), (6+6j), (9+9j)]