<small id='gVhMB'></small><noframes id='gVhMB'>

<i id='gVhMB'><tr id='gVhMB'><dt id='gVhMB'><q id='gVhMB'><span id='gVhMB'><b id='gVhMB'><form id='gVhMB'><ins id='gVhMB'></ins><ul id='gVhMB'></ul><sub id='gVhMB'></sub></form><legend id='gVhMB'></legend><bdo id='gVhMB'><pre id='gVhMB'><center id='gVhMB'></center></pre></bdo></b><th id='gVhMB'></th></span></q></dt></tr></i><div id='gVhMB'><tfoot id='gVhMB'></tfoot><dl id='gVhMB'><fieldset id='gVhMB'></fieldset></dl></div>

    <tfoot id='gVhMB'></tfoot>
      • <bdo id='gVhMB'></bdo><ul id='gVhMB'></ul>
    1. <legend id='gVhMB'><style id='gVhMB'><dir id='gVhMB'><q id='gVhMB'></q></dir></style></legend>

        格式化连续数字

        时间:2023-10-09
          <tfoot id='cZFGj'></tfoot>

          <small id='cZFGj'></small><noframes id='cZFGj'>

            <bdo id='cZFGj'></bdo><ul id='cZFGj'></ul>
            <legend id='cZFGj'><style id='cZFGj'><dir id='cZFGj'><q id='cZFGj'></q></dir></style></legend>

                <tbody id='cZFGj'></tbody>
                <i id='cZFGj'><tr id='cZFGj'><dt id='cZFGj'><q id='cZFGj'><span id='cZFGj'><b id='cZFGj'><form id='cZFGj'><ins id='cZFGj'></ins><ul id='cZFGj'></ul><sub id='cZFGj'></sub></form><legend id='cZFGj'></legend><bdo id='cZFGj'><pre id='cZFGj'><center id='cZFGj'></center></pre></bdo></b><th id='cZFGj'></th></span></q></dt></tr></i><div id='cZFGj'><tfoot id='cZFGj'></tfoot><dl id='cZFGj'><fieldset id='cZFGj'></fieldset></dl></div>

                • 本文介绍了格式化连续数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                  问题描述

                  我正在尝试使用 Python 格式化整数列表,但在实现我想要的结果时遇到了一些困难.

                  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"
                  

                  如果 Int 已经是连续的,我很难告诉我的代码忽略它.

                  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 :)

                  推荐答案

                  你可以像这样使用 itertools 模块中的 groupbycount:

                  You can use groupby and count from itertools module like this way:

                  感谢 @ason​​gtoruin 评论.要从输入中删除重复项,您可以使用:sorted(set(a)).

                  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]))
                  

                  输出:

                  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)
                  

                  输出:

                  1-3, 6, 8-9
                  

                  更新:

                  我猜,使用 itertools 模块可能会让许多 Python 的新开发人员感到困惑.这就是为什么我决定重写相同的解决方案而不导入任何包并尝试显示 groupbycount 在幕后所做的事情:

                  I'm guessing, using itertools modules may confuse many Python's new developers. This is why i decided to rewrite the same solution without importing any package and trying to show what groupby and count are doing behind the scenes:

                  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']
                  

                  这篇关于格式化连续数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:格式化浮点数时的Python格式默认舍入 下一篇:无法弄清楚字符串替换在 Python 3.x 中是如何工作

                  相关文章

                  最新文章

                • <tfoot id='aM5WF'></tfoot>
                    <bdo id='aM5WF'></bdo><ul id='aM5WF'></ul>
                  <i id='aM5WF'><tr id='aM5WF'><dt id='aM5WF'><q id='aM5WF'><span id='aM5WF'><b id='aM5WF'><form id='aM5WF'><ins id='aM5WF'></ins><ul id='aM5WF'></ul><sub id='aM5WF'></sub></form><legend id='aM5WF'></legend><bdo id='aM5WF'><pre id='aM5WF'><center id='aM5WF'></center></pre></bdo></b><th id='aM5WF'></th></span></q></dt></tr></i><div id='aM5WF'><tfoot id='aM5WF'></tfoot><dl id='aM5WF'><fieldset id='aM5WF'></fieldset></dl></div>
                    <legend id='aM5WF'><style id='aM5WF'><dir id='aM5WF'><q id='aM5WF'></q></dir></style></legend>

                      <small id='aM5WF'></small><noframes id='aM5WF'>