假设我有这个列表l
:
l = ['a', 'b', 'c', 'd', 'e']
我知道我可以使用.join
加入他们,逗号分隔为:
s = ', '.join(l)
>>> a, b, c, d, e
但我想在加入时尊重这些条件,很少有案例:
len(l) == 1
则输出应为a
len(l) == 2
则输出应为a and b
len(l) > 2 and len(l) < 5
则输出应为a, b, c and d
len(l) >= 5
:
len(l) == 5
则输出应为a, b, c, d and 1 other
len(l) > 5
则输出应为a, b, c, d and +(number of remaining strings) others
我尝试过的(工作):
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)
输出:
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
这段代码可以改进和折射吗?
答案 0 :(得分:3)
def display(l, t = 5):
length = len(l)
if length <= 2: print " and ".join(l)
elif length < threshold: print ", ".join(l[:-1]) + " and " + l[-1]
elif length == threshold: print ", ".join(l[:-1]) + " and 1 other"
else: print ", ".join(l[:t-1]) + " and +{} others".format(length - (t - 1))
<强>输出强>
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
答案 1 :(得分:0)
这正是你想要的:
def frmt_lst(l, limit=5):
if len(l) == 1:
return l[0]
if len(l) < limit:
return '{} and {}'.format(', '.join(l[:-1]), l[-1])
if len(l) == limit:
return '{} and 1 other'.format(', '.join(l[:-1]))
if len(l) > limit:
return '{} and {} others'.format(', '.join(l[:limit-1]), len(l[limit-1:]))
print frmt_lst(['a'])
print frmt_lst(['a', 'b'])
print frmt_lst(['a', 'b', 'c'])
print frmt_lst(['a', 'b', 'c', 'd'])
print frmt_lst(['a', 'b', 'c', 'd', 'e'])
print frmt_lst(['a', 'b', 'c', 'd', 'e', 'f'])
>>>
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
我注意到你只有四个特殊情况。所以我将代码更改为更容易。
答案 2 :(得分:0)
只是一个想法(可能过于复杂)
def join_func(inlist, threshold=5):
llen = len(inlist)
if llen==1:
return inlist[0]
suffix_len = llen - threshold
prefix = ','.join(inlist[:min(llen, threshold)-1*(suffix_len<=0)])
return ' and '.join([prefix, inlist[-1] if suffix_len<=0 else
'{} other{}'.format(suffix_len, 's'*(suffix_len>1))])
一些测试
In [69]: for l in xrange(1, 8):
print join_func(list(string.ascii_letters[:l]))
....:
a
a and b
a,b and c
a,b,c and d
a,b,c,d and e
a,b,c,d,e and 1 other
a,b,c,d,e and 2 others
答案 3 :(得分:0)
def frm_list(l, limit=5):
length = len(l)
if length == 1:
return l[0]
if length > limit:
l_joins = ', '.join(l[:limit-1])
others = length - limit
plural = others > 1 and 's' or ''
return u'{} and {} other{}'.format(l_joins, others, plural)
l_joins = ', '.join(l[:-1])
return u'{} and {}'.format(l_joins, l[-1])