【问题标题】:How can I make my output's print statement return the correct label and not the location of where that label is stored?如何使输出的打印语句返回正确的标签,而不是该标签的存储位置?
【发布时间】:2020-02-21 05:51:12
【问题描述】:

我正在为一个类定义一个函数,该函数从我读入的 CSV 文件中派生其值。该函数本质上是根据该城市记录中相关的纬度和经度值来查找两个城市之间的距离。

class City:
    def __init__ (self, name, label, lat, lon, pop_dict):
        self.name = name
        self.label = label
        self.lat = lat
        self.lon = lon
        self.pop_dict = pop_dict

    def printDistance(self, othercity):     
        lat_self = self.lat
        lat_othercity = othercity.lat
        lon_self = self.lon
        lon_othercity = othercity.lon
        lat1 = float(lat_self)
        lat2 = float(lat_othercity)
        lon1 = float(lon_self)
        lon2 = float(lon_othercity)
        radian_lat1 = math.radians(lat1)
        radian_lat2 = math.radians(lat2)
        radian_lon1 = math.radians(lon1)
        radian_lon2 = math.radians(lon2)
        AD = (math.acos(math.sin(radian_lat1) * math.sin(radian_lat2) + math.cos(radian_lat1) * math.cos(radian_lat2) * math.cos(radian_lon1 - radian_lon2)))
        print "The distance between", self, "and", othercity, "is", int((AD * 6300)), "kilometers."

print Cities[0].printDistance(Cities[1])

该功能按预期工作,但是我只能输入城市位置的索引值,而不是城市名称本身。所以对于上面的示例打印语句,我收到:The distance between <__main__.City instance at 0x103128d40> and <__main__.City instance at 0x1031285f0> is 5783 kilometers.

我希望我的语句能够运行,以便我可以简单地运行:例如print Cities[Tokyo].printDistance(Cities[Paris])

【问题讨论】:

  • 能否更清楚您的期望?你期望printDistance 的输出是什么? CitiesTokyo 定义在哪里?
  • @viniciusjssouza 感谢之前的回复,我现在收到了我期望的输出,即打印语句中的城市名称,而不是它们的索引位置。然而,我想要的是让我的打印语句接受实际的城市名称作为输入,而不是它们的索引号。例如,我现在有print Cities[0].printDistance(Cities[20]),它给了我想要的输出语句。但要使其工作,用户需要知道每个城市在 CSV 中的索引是什么。我想要一个 print 语句,它可以让 print 语句采用城市名称,而不是索引。

标签: python-2.7 list csv class


【解决方案1】:

如果您将print "The distance between", self, "and", othercity, "is", int((AD * 6300)), "kilometers." 更改为print "The distance between", self.name, "and", othercity.name, "is", int((AD * 6300)), "kilometers.",打印功能应该会显示城市名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多