zltzlt 发表于 2020-4-4 15:20:25

Python 实现 split_at()

本帖最后由 zltzlt 于 2020-4-4 17:28 编辑

Python 实现 split_at()

上代码:

def split_at(pred, iterable):
    """split_at(pred, iterable) --> """
    if not callable(pred):
      val = pred

      def pred(x):
            return x == val
    b = []
    for i in iterable:
      if pred(i):
            yield b
            b = []
      else:
            b.append(i)
    yield b


print(list(split_at("b", "abcdbecba")))               # Out: [['a'], ['c', 'd'], ['e', 'c'], ['a']]
print(list(split_at(lambda x: x % 2, range(10))))   # Out: [, , , , , []]
print(list(split_at(5, )))    # Out: [, , ]

如果代码有问题,欢迎在评论区指正{:10_311:}

sYMMetrY 发表于 2020-4-4 17:15:34

我想从实用的角度提一个建议:
sorted(iterable, *, key=None, reverse=False)就好比sorted()函数中的key值不一定是方程,也可以是none来表示按照从大到小的顺序排列;
如若实现这样的转变:
split_at(lambda x: x == "b", "abcdbecba")   ---> split_at( "b", "abcdbecba")    得到相同的结果 : [['a'], ['c', 'd'], ['e', 'c'], ['a']]使用更方便。

感觉这个还是蛮实用的一个函数。

若提的不对,还望见谅!{:10_297:}

zltzlt 发表于 2020-4-4 17:28:03

sYMMetrY 发表于 2020-4-4 17:15
我想从实用的角度提一个建议:
就好比sorted()函数中的key值不一定是方程,也可以是none来表示按照从大 ...

建议被采纳{:10_256:}

sYMMetrY 发表于 2020-4-4 17:39:58

zltzlt 发表于 2020-4-4 17:28
建议被采纳

{:10_264:}

永恒的蓝色梦想 发表于 2020-4-8 14:31:12

本帖最后由 永恒的蓝色梦想 于 2020-4-14 14:45 编辑

_no_arg=object()

def split(iterable,/,*,func=_no_arg,value=_no_arg):
    '''
    split(iterable) -> generator
    split(iterable,*,func=obj) -> generator
    split(iterable,*,value=obj) -> generator

    With no keyword argument, return a generator split iterable by True items.
    With 'func' specified, return a generator split iterable by items which func(item) is True.
    With 'value' specified, return a generator split iterable by items which is equal to value.
    '''

    #init
    if func is _no_arg:
      if value is _no_arg:
            func=bool
      
      else:
            func=lambda x:x!=value

    elif value is not _no_arg:
      raise ValueError("Cannot specify 'func' and 'value' at the same time")
   
    #main
    temp=[]

    for i in iterable:
      if func(i):
            yield temp
            temp=[]
      else:
            temp.append(i)

    yield temp我也写了一个{:10_297:}

PS:提个建议:你的代码在一个装有 类/函数/callable 的迭代对象里会出错,建议改一改
页: [1]
查看完整版本: Python 实现 split_at()