我需要根据它有多少项打印不同的列表:
例如:
[]
应输出{}
["Cat"]
应输出{Cat}
["Cat", "Dog"]
应输出{Cat and Dog}
["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方法吗?
答案 0 :(得分:1)
假设单词永远不会包含逗号。您可以改为使用 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}
答案 1 :(得分:1)
以下是我的观点:
class CustomList(list):
def __repr__(self):
if len(self) == 0:
return '{}'
elif len(self) == 1:
return '{%s}' % self[0]
elif len(self) == 2:
return '{%s and %s}' % (self[0], self[1])
else:
return '{' + ', '.join(str(x) for x in self[:-1]) + ' and %s}' % self[-1]
>>> my_list = CustomList()
>>> my_list
{}
>>> my_list.append(1)
>>> print(my_list)
{1}
>>> my_list.append('spam')
>>> print(my_list)
{1 and spam}
>>> my_list.append('eggs')
>>> my_list.append('ham')
>>> print(my_list)
{1, spam, eggs and ham}
>>> my_list
{1, spam, eggs and ham}
通过这种方式,您可以使用功能齐全的list
,只能自定义表示。