python - 使用 itemgetter 测试相等性

标签 python python-3.x python-itertools

from operator import itemgetter
from itertools import takewhile

xs = [ ('foo',1), ('bar',1), ('baz',2) ]

xs 按第二项排序 - 'bar' 之后不再有 1

def item_map(xs):
    getcount = itemgetter(1)
    return list(map(getcount,xs))

print(item_map(xs))
>>> [1, 1, 2]

返回每个元组的第二个元素的列表。

def item_take(xs):   
    return list(takewhile(lambda x: x[1] == 1, xs))

print(item_take(xs))
[('foo', 1), ('bar', 1)]

返回第二个元素 == 1 的元组。

def could_this_work(xs):
    match = itemgetter(1) == 1 
    return list(takewhile(match, xs))

print(could_this_work(xs))
TypeError: 'bool' object is not callable

不返回第二个元素为 == 1 的元组

有没有办法使用 itemgetter 代替 lambda?或者itemgetter可以不这样使用吗?

编辑。 takewhile 的使用是有原因的。我明白它的作用。该函数将用于排序列表。我很欣赏元组是向后的,但是我使用它的代码对于我想要和期望的是正确的。

最佳答案

您的 lambda 函数实际上是两个函数的组合:operator.itemgetter(1)operator.eq。以纯函数式方式执行此操作需要一个 compose() 函数,如下所示:

def compose(f, g):
    def composed(x):
        return f(g(x))
    return composed

使用这个函数,你可以做到

from operator import itemgetter, eq
from functools import partial

def take_items(a):
    return takewhile(compose(partial(eq, 1), itemgetter(1)), a)

不过,我认为这不是一个好主意。我可能会选择直接的方式

def take_items(a):
    for x in a:
        if x[1] != 1:
            break
        yield x

我认为这需要代码读者更少的思考。

关于python - 使用 itemgetter 测试相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11155957/

相关文章:

Python 二维数组求和枚举

python-3.x - Python 3.6.0 的 Pygame 安装

python - 在Python中生成n个组合的最快方法

python - 以某种方式迭代素数

Python限定组合

PythonAnywhere + 虚拟环境 : "Could not find platform dependent libraries <exec_prefix>..."

python - 我无法使用 pip 在 Windows 7 上安装 python 模块 cv2

python - key 错误 : SPARK_HOME during SparkConf initialization

python-3.x - 在 ipywidgets 交互式中排列小部件

python - BS4 + Python3 : unable to crawl tree: 'NavigableString' object has no attribute 'has_attr'