Custom string representation of a list based on the number of elements (Python)

Hi, the first poster is here.

I need to print the list differently depending on the number of its elements:

For instance:

  • Without elements, i.e. []should output{}
  • For 1 element, ie ["Cat"]should output{Cat}
  • For two elements, i.e. ["Cat", "Dog"]should output{Cat and Dog}
  • For 3 or more elements, i.e. ["Cat", "Dog", "Rabbit", "Lion"]should output{Cat, Dog, Rabbit and Lion}

I am currently doing something like this with if commands:

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?

+4
source share
2 answers

, . 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

:

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, .

+1

Source: https://habr.com/ru/post/1687057/


All Articles