Assume i have this list l
:
l = ['a', 'b', 'c', 'd', 'e']
I know i can join them using .join
with comma separated as:
s = ', '.join(l)
>>> a, b, c, d, e
But i want to respect these conditions while joining, few cases are:
- If
len(l) == 1
then output should be justa
- if
len(l) == 2
then output should bea and b
- if
len(l) > 2 and len(l) < 5
then output should bea, b, c and d
- if
len(l) >= 5
:- if
len(l) == 5
then output should bea, b, c, d and 1 other
- if
len(l) > 5
then output should bea, b, c, d and +(number of remaining strings) others
- if
What i have tried (working):
def display(l, threshold=4):
s = ''
if l:
c = len(l)
if c <= threshold:
if c == 1:
s = l[0]
else:
s = ', '.join(l[:-1])
s += ' and ' + l[-1]
else:
s = ', '.join(l[:threshold])
remaining = c - threshold
other = 'other' if remaining == 1 else 'others'
remaining = str(remaining) if remaining == 1 else '+' + str(remaining)
s += ' and %s %s' % (remaining, other)
print s
return s
if __name__ == '__main__':
l = ['a', 'b', 'c', 'd', 'e', 'f']
display(l[:1])
display(l[:2])
display(l[:3])
display(l[:4])
display(l[:5])
display(l)
Output:
a
a and b
a, b and c
a, b, c and d
a, b, c, d and 1 other
a, b, c, d and +2 others
Can this code be improved and refractor?
Output
Just a thought (maybe over-complicated)
Some test
This does just what you wanted:
I noticed you only really had four special cases. So I changed the code to be easier.