【问题标题】:Python analogue for Ruby Enumerable .partition method [duplicate]Ruby Enumerable .partition 方法的 Python 类似物
【发布时间】:2012-09-05 10:39:05
【问题描述】:

可能重复:
python equivalent of filter() getting two output lists (i.e. partition of a list)

python 标准库中是否有任何内置函数或某些模块,可以模拟 Ruby 中的 Enumerable.partition 行为,并仅对对象进行一次迭代以根据传递的谓词函数获取两个列表/元组?

【问题讨论】:

标签: python ruby standard-library


【解决方案1】:

无耻地从this question窃取-你可以使用itertoolstee函数:

from itertools import tee

def split_on_condition(seq, condition):
    l1,l2 = tee((condition(item),item) for item in seq)
    return (i for p, i in l1 if p), (i for p, i in l2 if not p)

【讨论】:

  • 不需要复制粘贴,完全一样的问题我们可以关闭
猜你喜欢
  • 2012-12-14
  • 2011-06-23
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多