因此,我有一组来自工厂传感器的位置数据。它以米为单位生成从x到y / z位置的x,y和z信息。我有一个函数,可以将距纬度/经度的距离转换为米,但是我需要在毕达哥拉斯函数中使用x和y数据来确定这一点。让我尝试用传感器提供的JSON数据示例进行说明。
[
{
"id": "84eb18677194",
"name": "forklift_0001",
"areaId": "Tracking001",
"areaName": "Hall1",
"color": "#FF0000",
"coordinateSystemId": "CoordSys001",
"coordinateSystemName": null,
"covarianceMatrix": [
0.82,
-0.07,
-0.07,
0.55
],
"position": [ #this is the x,y and z data, in meters from the ref point
18.11,
33.48,
2.15
],
在该分支中,铲车沿参考纬度/经度长18.11m,距纬度/经度高33.38m。传感器高2.15m,这是我不需要的恒定信息。要计算与参考点的距离,我需要使用毕达哥拉斯,然后将数据转换回经/纬度,以便我的分析工具可以显示出来。
我的问题(就python而言)是我不知道如何使它看到18.11和33.38作为x和y并告诉它完全忽略2.15。这是我到目前为止所拥有的。
import math
import json
import pprint
import os
from glob import iglob
rootdir_glob = 'C:/Users/username/Desktop/test_folder**/*"' # Note the
added asterisks, use forward slash
# This will return absolute paths
file_list = [f for f in
iglob('C:/Users/username/Desktop/test_folder/13/00**/*', recursive=True)
if os.path.isfile(f)]
for f in file_list:
print('Input file: ' + f) # Replace with desired operations
with open(f, 'r') as f:
distros = json.load(f)
output_file = 'position_data_blob_14' + str(output_nr) + '.csv' #output file name may be changed
def pythagoras(a,b):
value = math.sqrt(a*a + b*b)
return value
result = pythagoras(str(distro['position'])) #I am totally stuck here :/
print(result)
这段脚本是一个更广泛的项目的一部分,该项目可以按机器和人员以及每天的工作时间和非工作时间来解析文件。
如果有人可以给我一些有关如何使毕达哥拉斯零件起作用的提示,我将非常感激。我不确定是否应该将其定义为函数,但是当我键入此函数时,我想知道它是否应该是使用x和y并忽略x的“ for”循环。
非常感谢所有帮助。
答案 0 :(得分:1)
尝试一下:
position = distro['position'] # Get the full list
result = pythagoras(position[0], position[1]) # Get the first and second element from the list
print(result)
为什么将str()
用作函数的自变量?你想做什么?
答案 1 :(得分:1)
您正在将一个输入(一个数字列表)传递给一个以两个数字作为输入的函数。有两种解决方案-更改您的传递内容或更改功能。
distro['position'] = [18.11, 33.48, 2.15]
,因此对于第一个解决方案,您需要做的只是传递distro['position'][0]
和distro['position'][1]
:
result = pythagoras(distro['position'][0], distro['position'][1])
或者(我认为这更优雅),将列表传递给该函数,然后让该函数提取其关心的值:
result = pythagoras(distro['position'])
def pythagoras(input_triple):
a,b,c = input_triple
value = math.sqrt(a*a + b*b)
return value
答案 2 :(得分:0)
我使用的解决方案是
对于file_list中的f: print('输入文件:'+ f)#替换为所需的操作
with open(f, 'r') as f:
distros = json.load(f)
output_file = '13_01' + str(output_nr) + '.csv' #output file name may be changed
with open(output_file, 'w') as text_file:
for distro in distros:
position = distro['position']
result = math.sqrt(position[0]*position[0] + position[1]*position[1]),
print((result), file=text_file)
print('Output written to file: ' + output_file)
output_nr = output_nr + 1
答案 3 :(得分:-1)
您是否检查了要传递的参数的数据类型?
def pythagoras(a,b):
value = math.sqrt(int(a)**2 + int(b)**2)
return value
在整数的情况下。