Python将对象值转换为int

时间:2018-10-07 20:27:36

标签: python object math instance

我已经使用python一段时间了,但仍然遇到基本问题。 我目前在python中使用exifread库来获取经度和纬度。我需要将DMS值转换为DD。

到目前为止,我已经写了以下内容:

    #!/bin/python
import math
import exifread
path_name = './IMAG0658.jpg'
f = open(path_name, 'rb')

tags = exifread.process_file(f)

GPSLat = tags['GPS GPSLatitude']
print tags['GPS GPSLatitudeRef']
print GPSLat.values[0]
print GPSLat.values[1]
print GPSLat.values[2]
GPSDDLat = GPSLat.values[0] + ((GPSLat.values[1] / 60) + (GPSLat.values[2]/3600))
print GPSDDLat

但是在打印以下内容后会崩溃:

$python tempexif.py
N
33
52
433621/10000
Traceback (most recent call last):
  File "tempexif.py", line 14, in <module>
    GPSDDLat = GPSLat.values[0] + ((GPSLat.values[1] / 60) + (GPSLat.values[2]/3600))
TypeError: unsupported operand type(s) for /: 'instance' and 'int'

如何针对列表值而不是对象本身进行数学运算?

2 个答案:

答案 0 :(得分:1)

您的代码不完整,因为您没有提供输入文件package com.example.shubhojit.careersafter10th.ViewHolder; import android.content.res.AssetManager; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.shubhojit.careersafter10th.Interface.ItemClickListener; import com.example.shubhojit.careersafter10th.R; public class Courses_After10thViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView txtCourseName; public ImageView courseImage; public TextView txtCourseDuration; Typeface courseName; Typeface courseDuration; private ItemClickListener itemClickListener; public Courses_After10thViewHolder(View itemView) { super(itemView); txtCourseName = (TextView)itemView.findViewById(R.id.courses_after10th_name); courseImage = (ImageView)itemView.findViewById(R.id.courses_after10th_image); txtCourseDuration = (TextView)itemView.findViewById(R.id.courses_after10th_duration); courseName = Typeface.createFromAsset(context.getAssets(),"Fonts/Antipasto-RegularTrial.ttf"); itemView.setOnClickListener(this); } public void setItemClickListener(ItemClickListener itemClickListener) { this.itemClickListener = itemClickListener; } @Override public void onClick(View view) { itemClickListener.onClick(view,getAdapterPosition(),false); } } 。但是仍然可以说一些话,我们仍然可以回答您的问题。

在您的打印语句中,它们看起来像IMAG0658.jpgGPSLat.values[0]都是GPSLat.values[1]的值。但是我们看到int看起来像是一个分数,因此不是GPSLat.values[2]值。从错误跟踪中,我们可以看到intGPSLat.values[1]实际上是一个对象实例。因此,这些值中至少有一个像数字值一样打印,但实际上是一个对象实例。

您的问题的解决方案是采用GPSLat.values[2]函数中显示的那些显而易见的数值,并由此print函数也可以访问这些数值,并将其转换为数值,然后再进行进一步计算。由于str的打印效果不像int那样,而是打印的像分数一样,因此我们可以在GPSLat.values[2]模块中使用Fraction类型轻松地转换为fractions。因此,对于每个值,我们使用float来获取看起来像数字的值,然后将其转换为实际的数字str值。

所以我们可以做

float

但是如果没有该文件,我将无法对该代码进行实际检查。

答案 1 :(得分:0)

GPSLat.values[x]是一个对象(实例,如回溯中所说)。

为了获得学位,您需要做:

def val_2_deg(value):
    return float(value.num) / float(value.den)

,然后将公式更改为:

GPSDDLat = val_2_deg(GPSLat.values[0]) + val_2_deg(GPSLat.values[1])/60 + val_2_deg(GPSLat.values[2])/3600
相关问题