【问题标题】:Is there a str.split equivalent for lists in Python?Python中的列表是否有等效的str.split?
【发布时间】:2012-08-19 02:34:29
【问题描述】:

如果我有一个字符串,我可以使用 str.split 方法将其拆分为空格:

"hello world!".split()

返回

['hello', 'world!']

如果我有一个类似的列表

['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]

有没有split方法可以围绕None进行拆分并给我

[['hey', 1], [2.0, 'string', 'another string'], [3.0]]

如果没有内置方法,那么最 Pythonic/优雅的方法是什么?

【问题讨论】:

  • 您没有指定[None, 1, None, None, 2, None] 的行为,我认为应该产生[[],[1],[],[2],[]]

标签: python string list


【解决方案1】:

可以使用 itertools 生成简洁的解决方案:

groups = []
for k,g in itertools.groupby(input_list, lambda x: x is not None):
    if k:
        groups.append(list(g))

【讨论】:

  • 将您的 lambda 更改为 lambda x: x is not None,您可以将您的 if 语句简化为 if k(因为只有当该组不是 Nones 的一组时,k 才会为真) .很好的答案 - +1!
  • 或:groups = [list(g) for k, g in itertools.groupby(input_list, lambda x: x is not None if k]
【解决方案2】:

导入itertools.groupby,然后:

list(list(g) for k,g in groupby(inputList, lambda x: x!=None) if k)

【讨论】:

    【解决方案3】:

    没有内置的方法可以做到这一点。这是一种可能的实现方式:

    def split_list_by_none(a_list):
        result = []
        current_set = []
        for item in a_list:
            if item is None:
                result.append(current_set)
                current_set = []
            else:
                current_set.append(item)
        result.append(current_set)
        return result
    

    【讨论】:

      【解决方案4】:
      # Practicality beats purity
      final = []
      row = []
      for el in the_list:
          if el is None:
              if row:
                  final.append(row)
              row = []
              continue
          row.append(el)
      

      【讨论】:

      • @cmh - 基本上,如果你现在需要做某事,有时最简单的方法就是你需要的——避免花几个小时寻找最“Pythonic”的方法来做某事。但是,如果您找到更好的方法来做到这一点(正如您的答案肯定是),那么请务必使用它:-)
      【解决方案5】:
      def splitNone(toSplit:[]):
          try:
              first = toSplit.index(None)
              yield toSplit[:first]
              for x in splitNone(toSplit[first+1:]):
                  yield x
          except ValueError:
              yield toSplit
      

       

      >>> list(splitNone(['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]))
      [['hey', 1], [2.0, 'string', 'another string'], [3.0]]
      

      【讨论】:

        猜你喜欢
        • 2013-06-25
        • 2018-05-03
        • 2016-05-26
        • 2018-11-21
        • 2013-02-04
        • 2012-11-21
        • 2019-03-23
        • 1970-01-01
        • 2011-09-23
        相关资源
        最近更新 更多