public **partial** class launcher5Page : ContentPage
{
public launcher5Page()
{
InitializeComponent();
webview1.Source = "web address here";
}
public **static** bool changeURL(string urlString)
{
**webview1**.Source = urlString;
return true;
}
}
此代码尝试使用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__()
不会排序到正确的顺序。
答案 0 :(得分:6)
您将经度和纬度比作字符串,而不是数字。因此,它们按字典顺序而不是数字进行比较,因此'104'
将在 '80'
之前对进行排序,因为'1'
位于ASCII表中的'8'
之前(它没有& #39;重要的是跟随其他人物。)
将您的值转换为浮点数:
self._latitude = float(self._string[2])
self._longitude = float(self._string[3])
你的比较有一个小错误;如果经度和纬度都匹配,则返回None
而不是False
。您可能想要测试相等性并应用@functools.total_ordering()
decorator而不是假设只调用__lt__()
。
稍微清理代码(并删除name()
和location()
方法,只需使用name
和location
属性):
from functools import total_ordering
@total_ordering
class City:
def __init__(self, string):
self.name, self.state, lat, long = string.split(',')
self.location = (self._latitude, self._longitude) = float(lat), float(long)
def __lt__(self, other):
if not isinstance(other, City):
return NotImplemented
# tuples defer ordering to the contents; compare them
# in (longitude, latitude) order so that if longitude is
# equal, the outcome is based on latitude.
return self.location[::-1] < other.location[::-1]
def __eq__(self, other):
if not isinstance(other, City):
return NotImplemented
return self.location == other.location
请注意,__lt__()
实际上只需要比较self.location
;元组排序负责其余的事情:
sortednames = [c.name for c in sorted(map(City, citystrings), reverse=True)]
注意reverse=True
;你希望首先列出较大的值(格林威治以西)(