格式化连续的数字 [英] Formatting consecutive numbers
问题描述
输入是一个整数列表:
list = [ 1,2,3,6,8,9]
我想输出为看起来像这样的字符串:
outputString =1-3,6,8-9
$ c
$ b $ p
$ b
code> outputString =1-2-3,6,8-9
I如果它已经是连续的,那就麻烦告诉我的代码忽略一个Int。
这是我的代码到目前为止:
$ b
def format(l ):
i = 0
outputString = str(l [i])
在范围内(len(l)-1):
如果l [i + 1] = = l [i] +1:
outputString + =' - '+ str(l [i + 1])$ b $ b else:
outputString + =','+ str(l [i +1])$ b $ bi = i + 1
return outputString
感谢您的帮助和见解:)
您可以使用 groupby
和 count
来自 itertools
模块就像这样:
编辑:
感谢 @asongtoruin
评论。为了从输入中删除重复项,可以使用: sorted(set(a))
。
from itertools import groupby,count
a = [1,2,3,6,8,9]
clustered = [list(v)for _,v in groupby (排序(a),lambda n,c = count():n-next(c))]
for clustering:
if len(k)> 1:
print({0} - {1}。format(k [0],k [-1]))
else:
print({0})输出:
1-3
6
8-9
或者也许你可以做这样的事情,以获得一个漂亮的输出:
from itertools import groupby计数
a = [1,2,3,6,8,9]
clustered = [list(v)for _,v in groupby(sorted(a),lambda n ([{0} - {1})。format(k [0],k [-1],c = count():n-next(c))]
out =,.join )如果len(k)> 1否则{0}。格式(k [0])为k在群集中])
print(out)
$ c $输出: 1-3,
$输出: 6,8-9
I'm trying to format a list of integers with Python and I'm having a few difficulties achieving what I'd like.
Input is a sorted list of Integers:
list = [1, 2, 3, 6, 8, 9]
I would like it the output to be a String looking like this:
outputString = "1-3, 6, 8-9"
So far all I managed to achieve is this:
outputString = "1-2-3, 6, 8-9"
I'm having trouble to tell my code to ignore a Int if it was already consecutive.
Here is my code so far:
def format(l):
i = 0
outputString = str(l[i])
for x in range(len(l)-1):
if l[i + 1] == l[i]+1 :
outputString += '-' + str(l[i+1])
else :
outputString += ', ' + str(l[i+1])
i = i + 1
return outputString
Thanks for your help and insights :)
解决方案 You can use groupby
and count
from itertools
module like this way:
Edit:
Thanks to @asongtoruin
comment. For removing duplicates from the input you can use: sorted(set(a))
.
from itertools import groupby, count
a = [1, 2, 3, 6, 8, 9]
clustered = [list(v) for _,v in groupby(sorted(a), lambda n, c = count(): n-next(c))]
for k in clustered:
if len(k) > 1:
print("{0}-{1}".format(k[0], k[-1]))
else:
print("{0}".format(k[0]))
Output:
1-3
6
8-9
Or maybe you can do something like this in order to have a pretty output:
from itertools import groupby, count
a = [1, 2, 3, 6, 8, 9]
clustered = [list(v) for _,v in groupby(sorted(a), lambda n, c = count(): n-next(c))]
out = ", ".join(["{0}-{1}".format(k[0], k[-1]) if len(k) > 1 else "{0}".format(k[0]) for k in clustered ])
print(out)
Output:
1-3, 6, 8-9
这篇关于格式化连续的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!