有效地连接地址行
Concatenate address lines efficiently
我的数据库存储了一些标准地址行字段(地址行 1,2.. 城市、国家/地区,Postal/zip 代码),我想将它们连接成人类形式。我已经编写了以下代码,但我不确定使用一堆 if 语句是否非常有效。 (写在python不过是我关心的算法)
def human_readable_address(self):
'''
Return human readable address
If address1 is empyty, return None
'''
addr = ""
if(self.address1):
addr += self.address1 + ", "
else:
return None
if(self.address2):
addr += self.address2 + ", "
if(self.city):
addr += self.city + ", "
if(self.postal_code):
addr += self.postal_code + ", "
if(self.country):
addr += self.country + ", "
return addr
大家怎么看?有没有更好的方法?
您可以使用 str.join()
:
而不是使用字符串连接(每次都会创建一个新字符串)
def human_readable_address(self):
'''
Return human readable address
If address1 is empty, return None
'''
if not self.address1:
return None
return ', '.join(filter(None, [self.address1, self.address2, self.city,
self.postal_code, self.country]))
您可以使用列表理解,连接成一个字符串,以您需要的格式获取地址:
address_1 = "first"
address_2 = False
address_3 = "third"
def make_address(*args):
return "".join(["%s,\n" % x for x in args if x])[:-2]
address = make_address(address_1, address_2, address_3)
print(address)
我的数据库存储了一些标准地址行字段(地址行 1,2.. 城市、国家/地区,Postal/zip 代码),我想将它们连接成人类形式。我已经编写了以下代码,但我不确定使用一堆 if 语句是否非常有效。 (写在python不过是我关心的算法)
def human_readable_address(self):
'''
Return human readable address
If address1 is empyty, return None
'''
addr = ""
if(self.address1):
addr += self.address1 + ", "
else:
return None
if(self.address2):
addr += self.address2 + ", "
if(self.city):
addr += self.city + ", "
if(self.postal_code):
addr += self.postal_code + ", "
if(self.country):
addr += self.country + ", "
return addr
大家怎么看?有没有更好的方法?
您可以使用 str.join()
:
def human_readable_address(self):
'''
Return human readable address
If address1 is empty, return None
'''
if not self.address1:
return None
return ', '.join(filter(None, [self.address1, self.address2, self.city,
self.postal_code, self.country]))
您可以使用列表理解,连接成一个字符串,以您需要的格式获取地址:
address_1 = "first"
address_2 = False
address_3 = "third"
def make_address(*args):
return "".join(["%s,\n" % x for x in args if x])[:-2]
address = make_address(address_1, address_2, address_3)
print(address)