我在 codewars 上遇到了一个问题,我不确定这两种可能的解决方案之间有什么区别,一种是将列表转换为元组,另一种是指定输入列表的元素。
问题:将姓名(字符串)列表转换为类似于 Facebook 用来显示喜欢的语句:“Alex 喜欢这个”、“Alex 和 John 喜欢这个”、“Alex、John 和其他 2 个喜欢这个”等。
使用 if-elif-etc 语句,这非常简单:
if len(names) == 0:
output_string = "no one likes this"
elif len(names) == 1:
output_string = str(names[0]) + " likes this"
Run Code Online (Sandbox Code Playgroud)
但是在较长的姓名列表中,您可以选择:
elif len(names) == 2:
output_string = "%s and %s like this" % (names[0], names[1])
Run Code Online (Sandbox Code Playgroud)
或者
elif len(names) == 3:
output_string = "%s, %s and %s like this" % tuple(names)
Run Code Online (Sandbox Code Playgroud)
我的假设是使用names[0]etc 的计算效率更高,因为您没有在内存中为元组创建新对象 - 是吗?