我试图用Python格式化一个整数列表,而且我在实现我想要的东西时遇到了一些困难。
输入是整数的排序列表:
list = [1, 2, 3, 6, 8, 9]我希望输出是如下所示的字符串:
outputString = "1-3, 6, 8-9"到目前为止,我所取得的成就是:
outputString = "1-2-3, 6, 8-9"如果Int已经是连续的,我很难告诉我的代码忽略它。
到目前为止,我的代码如下:
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谢谢你的帮助和见解:)
发布于 2017-03-16 18:09:02
您可以从groupby模块中使用itertools和count,如下所示:
编辑:
感谢@asongtoruin的评论。用于从输入中删除重复项,可以使用: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]))输出:
1-3
6
8-9或者你可以这样做,这样才能有一个很好的输出:
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)输出:
1-3, 6, 8-9更新:
我猜想,使用迭代工具模块可能会使许多Python的新开发人员感到困惑。这就是为什么我决定重写相同的解决方案,而不导入任何包,并试图在幕后展示groupby和count在做什么:
def count(n=0, step=1):
"""Return an infinite generator of numbers"""
while True:
n += step
yield n
def concat(lst):
"""Group lst elements based on the result of elm - next(_count)"""
_count, out = count(), {}
for elm in sorted(lst):
c = elm - next(_count)
if c in out:
out[c].append(elm)
else:
out[c] = [elm]
return out
def pretty_format(dct):
for _, value in dct.items():
if len(value) > 1:
yield '{}-{}'.format(value[0], value[-1])
else:
yield '{}'.format(value[0])
lst = [1, 2, 3, 6, 8, 9]
dct = concat(lst)
formatted = list(pretty_format(dct))
print(formatted)输出:
['1-3', '6', '8-9']发布于 2017-03-16 18:37:28
list=[1, 2, 3, 4, 6, 10, 11, 12, 13]
y=str(list[0])
for i in range(0, len(list)-1):
if list[i+1] == list[i]+1 :
y+= '-' + str(list[i + 1])
else:
y+= ',' + str(list[i + 1])
print y
z= y.split(',')
outputString= ''
for i in z:
p=i.split('-')
if p[0] == p[len(p)-1]:
outputString = outputString + str(p[0]) + str(',')
else:
outputString = outputString + str(p[0]) + str('-') + str(p[len(p) - 1]) + str(',')
outputString = outputString[:len(outputString) - 1]
print 'final ans: ',outputString在代码后面添加这些行。
发布于 2017-03-16 18:38:16
因为发布这个解决方案的另一个人删除了他的答案..。
下面是一个O(n)字符串构建解决方案:
def stringify(lst):
result = str(lst[0])
end = None
for index, num in enumerate(lst[1:]):
if num - 1 == lst[index]: # the slice shifts the index by 1 for us
end = str(num)
else:
if end:
result += '-' + end
end = None
result += ', ' + str(num)
# Catch the last term
if end:
result += '-' + str(num)
return resulthttps://stackoverflow.com/questions/42841514
复制相似问题