ルネ・マルティネス:
私は - 私は数XとY座標のための各リストのリストに指定して、この問題を抱えていると私は最初、私は、次のコードを持っていることのために、リストの座標に最も近い座標のどの見つけなければなりません。
import math
list1 = [1, 2, 1, 1]
list2 = [4, 7, 6, 3]
if len(list2) == len(list1):
print ("number of elements does match\n")
else:
print ("number of elements doesnt match\n")
a=1
dist_list = []
for i in range(1, len(list1)):
x1 = list1[0]
y1 = list2[0]
x2 = list1[a]
y2 = list2[a]
dist = abs(math.sqrt((x1-(x2)**2) - (y1-(y2)**2)))
a=a+1
dist_list.append(dist)
print ("distancias:", dist_list, "\n")
for element in iterable:
if element:
return
return False
print(list1[b],",",list2[b], "es la coordenada mas cercana")
# "is the closest coordinate"
この場合には、座標間の距離は、座標1,3 1,4に最も近いことを示しています。
distancias: [6.48074069840786, 5.656854249492381, 2.23606797749979]
私はここでそれを言う必要があります。 print(list1[b],",",list2[b], "es la coordenada mas cercana")
私が検索し、発見されているany()
機能を、私は式を再作成することができる方法があるPythonドキュメントによると:
def any(iterable):
for element in iterable:
if element:
return True
return False
しかし、私は私が望ましい結果を得るためにのためにそれを再作成する方法を見てcan't。また、私はこの演習のために私が唯一使用できると言わなければならないfor
、in
、while
、sqer、ABSとappend
。
簡単:
any()
このため無用です。あなたは、再作成する必要がmin()
(むしろ多分かnumpy.argmin()
)
あなたは開始時に第一の距離を取得し、他のすべての値と比較し、他の値が小さい場合、その値とそのインデックスを維持する必要があります。
b = 0 # get first index
b_value = dist_list[0] # get first value
# compare with other distances
for i in range(1, len(dist_list)):
if dist_list[i] < b_value: # if new distance is smaller
b = i # keep new index
b_value = dist_list[i] # keep new value
b = b+1 # because `dist_list[0]` has value for `list1[1]`, not `list1[0]`
(ところで:通常、私が使用するenumerate()
のではなく、range(len())
私はあなたがそれを知っていないと仮定します)
EDIT: @Tomerikooが指摘したように、距離の計算式が間違っています。そのはず:
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
完全なコード
import math
list1 = [1, 2, 1, 1]
list2 = [4, 7, 6, 3]
if len(list2) == len(list1):
print ("number of elements does match\n")
else:
print ("number of elements doesnt match\n")
dist_list = []
x1 = list1[0]
y1 = list2[0]
for i in range(1, len(list1)):
x2 = list1[i]
y2 = list2[i]
#dist = abs(math.sqrt((x1-(x2)**2) - (y1-(y2)**2)))
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
dist_list.append(dist)
print ("distancias:", dist_list, "\n")
b = 0
b_value = dist_list[0]
for i in range(1, len(dist_list)):
if dist_list[i] < b_value:
b = i
b_value = dist_list[i]
b = b+1 # because `dist_list[0]` has value for `list1[1]`, not `list1[0]`
print(list1[b],",",list2[b], "es la coordenada mas cercana")
# "is the closest coordinate"