[英]Custom string representation of list depending on number of items (Python)
I need to print out a list differently depending on how many items it has: 我需要根据它有多少项打印出不同的列表:
For example: 例如:
[]
should output {}
[]
应输出{}
["Cat"]
should output {Cat}
["Cat"]
应输出{Cat}
["Cat", "Dog"]
should output {Cat and Dog}
["Cat", "Dog"]
应该输出{Cat and Dog}
["Cat", "Dog", "Rabbit", "Lion"]
should output {Cat, Dog, Rabbit and Lion}
["Cat", "Dog", "Rabbit", "Lion"]
应输出{Cat, Dog, Rabbit and Lion}
I currently am doing something like this with a bunch of if statements: 我目前正在用一堆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
Is there a more pythonic way to do this? 是否有更多的pythonic方式来做到这一点?
Assuming the words will never contain commas themselves. 假设单词永远不会包含逗号。 You could instead use join and replace to deal with all your cases in just one line:
您可以使用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}
Here's how I'd go about this: 以下是我如何做到这一点:
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}
This way you have a fully functional list
, only the representation is customised. 这样您就拥有了一个功能齐全的
list
,只有表示是自定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.