【问题标题】:How to use Python's groupby [duplicate]如何通过[重复]使用Python组
【发布时间】:2013-09-09 04:30:11
【问题描述】:

如何将字符串拆分为 2,例如“string”将拆分为“st”、“ri”、“ng”组。 我检查了文档,来自 itertools 的 groupby 似乎是我需要的。但是,有没有办法简单地通过不使用 itertools 来做到这一点? 谢谢

【问题讨论】:

标签: python string itertools


【解决方案1】:

不用 itertools 也可以,但是会慢一些。除非是学习练习,否则请使用 itertools page: 中的“石斑鱼”食谱

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

【讨论】:

  • 注意izip_longest需要Python 2.6+
  • 我更喜欢链接问题中的@nosklo's answer,因为它没有版本限制
  • 依赖于 2008 年发布的 Python 2.6,几乎没有严重的版本限制。
  • 谢谢。我想如果我将我的脚本编译为可执行文件,它可能没有版本限制?
  • @dorothy 如果您使用py2exefreeze,您使用的版本已与程序捆绑在一起,因此您不必担心版本。
【解决方案2】:
s='your input string'
ans=[  ]
i=0
while i < len(s):
    ans.append( s[ i:i+2 ] )
    i+=2
print ans

【讨论】:

    【解决方案3】:

    如果你只想在没有itertools的情况下做两个字符组,你可以使用这个:

    s = 'string'
    groups = [''.join(g) for g in zip(s[:-1:2], s[1::2])]
    

    请注意,这只适用于偶数长度的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多