class City:
def __init__(self, string):
self._string = string.split(',')
self._name = self._string[0]
self._state = self._string[1]
self._latitude = self._string[2]
self._longitude = self._string[3]
self._location = [self._latitude, self._longitude]
def name(self):
return self._name
def location(self):
return self._location
self.hand.sort(key=lambda x: x.longitude)
def __lt__(self, other):
if self._longitude < other._longitude:
return True
if self._longitude > other._longitude:
return False
if self._longitude == other._longitude:
if self._latitude < other._latitude:
return True
if self._latitude > other._latitude:
return False
citystrings = ["Charleston,WV,38.35,81.63",
"Charlotte,NC,35.23,80.83",
"Cheyenne,WY,41.15,104.87",
"Chicago,IL,41.83,87.62",
"Cincinnati,OH,39.13,84.50",
"Cleveland,OH,41.47,81.62",
"Columbia,SC,34.00,81.03",
"Columbus,OH,40.00,83.02",
"Dallas,TX,32.77,96.77",
"Denver,CO,39.75,105.00"]
westtoeastnames = [
"Denver",
"Cheyenne",
"Dallas",
"Chicago",
"Cincinnati",
"Columbus",
"Charleston",
"Cleveland",
"Columbia",
"Charlotte",
]
cities = [City(s) for s in citystrings]
cities.sort()
sortednames = [c.name() for c in cities]
print(sortednames)
print(westtoeastnames)
['Cheyenne', 'Denver', 'Charlotte', 'Columbia', 'Cleveland', 'Charleston', 'Columbus', 'Cincinnati', 'Chicago', 'Dallas']
['Denver', 'Cheyenne', 'Dallas', 'Chicago', 'Cincinnati', 'Columbus', 'Charleston', 'Cleveland', 'Columbia', 'Charlotte']
此代码尝试使用__lt__()
对城市进行排序,根据它们在西边的距离和经度位于本初子午线以西。我在类中编写了一个__lt__()
方法,但是citystrings
无法按正确的顺序排序。你知道吗
您将经度和纬度作为字符串进行比较,而不是数字。因此,它们是按字典进行比较的,而不是按数字进行比较的,因此
'104'
将把排序在'80'
之前,因为在ASCII表中'1'
排在'8'
之前(后面跟什么字符都不重要)。你知道吗将值转换为浮点数:
您的比较有一个小错误;如果经度和纬度都匹配,则返回} decorator ,而不是假设只调用
None
,而不是False
。您可能希望测试等式并应用^{__lt__()
。你知道吗稍微清理一下代码(删除
name()
和location()
方法,只需使用name
和location
属性):请注意,
__lt__()
实际上只需要比较self.location
;元组排序处理其余部分:注意
reverse=True
;您希望首先列出较大的值(离格林威治更远的西部)。你知道吗相关问题 更多 >
编程相关推荐