2 回答
TA贡献1784条经验 获得超9个赞
编辑:看来您甚至不需要实施__eq__. 下面的示例无需实现即可工作__eq__。
您可以将每个地址映射到实现的单独类,__lt__然后__eq__根据该类进行排序。例如:
from __future__ import annotations
from typing import Text, Tuple
def parse_address(address: Text) -> Tuple[int, Text]:
"""I haven't extensively tested this yet.."""
first_space = address.find(' ')
if first_space == -1:
raise ValueError('Invalid address')
return int(address[:first_space]), address[first_space + 1:]
class CustomComparator(object):
def __init__(self, address: Text):
self._full_address = address
self._number, self._address = parse_address(address)
def __lt__(self, other: CustomComparator) -> bool:
if self._number != other._number:
return self._number < other._number
return self._address < other._address
# __str__ and __repr__ are just so printing appears cleaner in this case.
def __str__(self) -> Text:
return self._full_address
def __repr__(self) -> Text:
return str(self)
address_list = ['100 Parker St, Springfield, MA', '131 Parker St, Springfield, MA', '102 Boston Rd, Springfield, MA',
'181 Boston Rd, Springfield, MA', '150 King St, Springfield, MA', '103 King St, Springfield, MA',
'103 Boston Rd, Spingfield, MA']
address_list = [CustomComparator(address) for address in address_list]
address_list.sort()
print('\n'.join([str(address) for address in address_list]))
这将首先按数字排序地址,然后按字母顺序排序。在此示例中,它打印:
100 Parker St, Springfield, MA
102 Boston Rd, Springfield, MA
103 Boston Rd, Spingfield, MA
103 King St, Springfield, MA
131 Parker St, Springfield, MA
150 King St, Springfield, MA
181 Boston Rd, Springfield, MA
TA贡献1839条经验 获得超15个赞
你是什么意思
按数字和字母顺序
如果您的意思是您想按数字排序第一个,然后按数字旁边的字母排序,并且数字具有固定长度(如您的示例中的 3)sorted功能会自动执行此操作。如果数字长度不相等,您可以在前面填充一些额外的零并将其用作排序函数的键
address_list = ['100 Parker St, Springfield, MA','13 Parker St, Springfield, MA', '102 Boston Rd, Springfield, MA', '18 Boston Ad, Springfield, MA','103 Boston St, Springfield, MA','103 Aing St, Springfield, MA', '150 King St, Springfield, MA','103 King St, Springfield, MA']
pad_zeros = lambda x: "0"*(6-len(x[1])) + x[1]+ " "
key = lambda s: re.sub("(^\d*)\s?", pad_zeros, s)
sorted(address_list, key=key)
输出
['13 Parker St, Springfield, MA',
'18 Boston Ad, Springfield, MA',
'100 Parker St, Springfield, MA',
'102 Boston Rd, Springfield, MA',
'103 Aing St, Springfield, MA',
'103 Boston St, Springfield, MA',
'103 King St, Springfield, MA',
'150 King St, Springfield, MA']
添加回答
举报