我怎样才能更好地重构这个 python 脚本?
How can I refactor this python script better?
我希望确保代码中没有不必要的代码行。有没有办法重构它并获得相同的输出?
def format_name(first_name, last_name):
if len(first_name) > 0 and len(last_name) > 0:
return("Name: " + last_name + ", " + first_name)
elif len(first_name) > 0 or len(last_name) > 0:
return("Name: " + first_name + last_name)
else:
empty_string = ""
return empty_string
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))
# Should return an empty string
重构方法尝试在单个 if
条件下分配函数逻辑。
def format_name(first_name, last_name):
result = ''
sep = ', ' if first_name and last_name else ' '
if first_name or last_name:
result = last_name + sep + first_name
result = 'Name: ' + result.strip()
return result
print(format_name("Ernest", "Hemingway")) # "Name: Hemingway, Ernest"
print(format_name("", "Madonna")) # "Name: Madonna"
print(format_name("Voltaire", "")) # "Name: Voltaire"
print(format_name("", "")) # `empty_string`
在不“打高尔夫球”的情况下,这应该可以解决问题:
def format_name(first_name, last_name):
name = f"{first_name}, {last_name}".strip(", ")
return f"Name: {name}" if name else ""
使用str.join
和filter
构建名称字符串:
def format_name(first_name, last_name):
full_name = ", ".join(filter(None, (last_name, first_name)))
if full_name:
full_name = "Name: " + full_name
return full_name
我希望确保代码中没有不必要的代码行。有没有办法重构它并获得相同的输出?
def format_name(first_name, last_name):
if len(first_name) > 0 and len(last_name) > 0:
return("Name: " + last_name + ", " + first_name)
elif len(first_name) > 0 or len(last_name) > 0:
return("Name: " + first_name + last_name)
else:
empty_string = ""
return empty_string
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))
# Should return an empty string
重构方法尝试在单个 if
条件下分配函数逻辑。
def format_name(first_name, last_name):
result = ''
sep = ', ' if first_name and last_name else ' '
if first_name or last_name:
result = last_name + sep + first_name
result = 'Name: ' + result.strip()
return result
print(format_name("Ernest", "Hemingway")) # "Name: Hemingway, Ernest"
print(format_name("", "Madonna")) # "Name: Madonna"
print(format_name("Voltaire", "")) # "Name: Voltaire"
print(format_name("", "")) # `empty_string`
在不“打高尔夫球”的情况下,这应该可以解决问题:
def format_name(first_name, last_name):
name = f"{first_name}, {last_name}".strip(", ")
return f"Name: {name}" if name else ""
使用str.join
和filter
构建名称字符串:
def format_name(first_name, last_name):
full_name = ", ".join(filter(None, (last_name, first_name)))
if full_name:
full_name = "Name: " + full_name
return full_name