我需要根据它有多少项目来打印出不同的列表:
例如:
- 对于没有项目,即
[]
应该输出{}
- 对于 1 个项目,即
["Cat"]
应该输出{Cat}
- 对于 2 个项目,即
["Cat", "Dog"]
应该输出{Cat and Dog}
- 对于 3 个或更多项目,即
["Cat", "Dog", "Rabbit", "Lion"]
应该输出{Cat, Dog, Rabbit and Lion}
我目前正在用一堆 if 语句做这样的事情:
def customRepresentation(arr):
if len(arr) == 0:
return "{}"
elif len(arr) == 1:
return "{" + arr[0] + "}"
elif len(arr) == 2:
return "{" + arr[0] + " and " + arr[0] + "}"
else:
# Not sure how to deal with the case of 3 or more items
是否有更 pythonic 的方法来做到这一点?
最佳答案
假设单词本身永远不会包含逗号。您可以改用 join 和 replace 在一行中处理所有案例:
>>> def custom_representation(l):
... return "{%s}" % " and ".join(l).replace(" and ", ", ", len(l) - 2)
...
>>> for case in [], ["Cat"], ["Cat", "Dog"], ["Cat", "Dog", "Rabbit", "Lion"]:
... print(custom_representation(case))
...
{}
{Cat}
{Cat and Dog}
{Cat, Dog, Rabbit and Lion}
关于python - 列表的自定义字符串表示取决于项目数 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616102/