【问题标题】:Sort string into a list on python [duplicate]将字符串排序到python上的列表中[重复]
【发布时间】:2017-05-15 12:14:21
【问题描述】:

我需要在 python 上将字符串 'abcdef' 放入列表 ['ab', 'cd', 'ef'] 我尝试使用list(),但它返回['a', 'b', 'c', 'd',' 'e, 'f']

有人可以帮忙吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用zip:

    s = "abcdef"
    [''.join(x) for x in zip(s[::2], s[1::2])]
    # ['ab', 'cd', 'ef']
    

    或者

    [s[i:i+2] for i in range(0, len(s), 2)]
    # ['ab', 'cd', 'ef']
    

    【讨论】:

      【解决方案2】:

      如果你不介意额外的功能,你可以使用这样的东西:

      def grouper(string, size):
          i = 0
          while i < len(string):
              yield string[i:i+size]
              i += size
      

      这是一个生成器,因此您需要收集它的所有部分,例如使用list

      >>> list(grouper('abcdef', 3))
      ['abc', 'def']
      >>> list(grouper('abcdef', 2))  # <-- that's what you want.
      ['ab', 'cd', 'ef']
      

      【讨论】:

        猜你喜欢
        • 2014-10-04
        • 2021-01-25
        • 2012-07-22
        • 1970-01-01
        • 2016-12-25
        • 2021-07-10
        • 2013-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多