在python中给出一个条件,获取一个唯一的列表/元组元素

时间:2021-02-17 14:32:50

How do I get a tuple/list element given a condition in python? This occurs pretty often and I am looking for a nice-few-lines-pythonic way of doing this.

如何在python中给出一个条件的元组/列表元素?这经常发生,我正在寻找一个很好的几行 - pythonic方式来做到这一点。

here could be an example:

这可能是一个例子:

Consider a tuple containing 2D points coordinates like this:

考虑一个包含2D点坐标的元组,如下所示:

points = [[x1, y1],[x2, y2],[x3, y3], ...]

And I would like to get the point that minimizes the euclidean distance given an arbitrary point (say [X, Y] for instance, my point is : it is not contained in the list!)

而且我想得到的观点是,在给定任意点的情况下最小化欧氏距离(比如说[X,Y],我的观点是:它不包含在列表中!)

def dist(p1, p2):
    return sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2)
pointToCompare2 = [X, Y]

Anyone having a freaky one liner(or not) for that? Thanks!

谁有一个怪异的一个班轮(或没有)呢?谢谢!

2 个解决方案

#1


min(points, key=lambda x: dist(pointToCompare2, x))

min is a built-in function.

min是一个内置函数。

#2


v = [1,3,2,4,7,3,3,4,5,11]

def get_num_uniques(v):
    count = []
    dup = []
tmp = []
for i in v:
    if i not in count:
        count.append(i)
    else:
        dup.append(i)
        count.remove(i)
for j in count:
    if j not in dup:
        tmp.append(j)

return tmp

#Call the function
print get_num_uniques(v)

#1


min(points, key=lambda x: dist(pointToCompare2, x))

min is a built-in function.

min是一个内置函数。

#2


v = [1,3,2,4,7,3,3,4,5,11]

def get_num_uniques(v):
    count = []
    dup = []
tmp = []
for i in v:
    if i not in count:
        count.append(i)
    else:
        dup.append(i)
        count.remove(i)
for j in count:
    if j not in dup:
        tmp.append(j)

return tmp

#Call the function
print get_num_uniques(v)