2017-10-07 88 views
4

您好第一次在這裏發佈海報。根據項目數量自定義字符串表示形式(Python)

我需要以不同的方式打印出清單取決於它有多少項目有:

例如:

  • 對於任何項目,即[]應該輸出{}
  • 對於1項即["Cat"]應輸出{Cat}
  • 對於2項,即["Cat", "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 

有沒有更Python的方式做到這一點?

回答

1

假設單詞永遠不會包含逗號本身。你也可以使用joinreplace來處理所有的情況下,在短短的一行:

>>> 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} 
+0

請注意詞語本身包含逗號的情況。 –

+0

加入','可能會更有效率,只用'和'來替換最後一個? –

+1

這些詞將永遠不會包含逗號。 – XaddieMiegler

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,只有表示是自定義的。