Python 标准库有返回索引 0 处的值的函数吗?换句话说:
zeroth = lambda x: x[0]
我需要在像 map()
这样的高阶函数中使用它。我问是因为我相信使用可重用函数比定义自定义函数更清楚 - 例如:
pairs = [(0,1), (5,3), ...]
xcoords = map(funclib.zeroth, pairs) # Reusable
vs.
xcoords = map(lambda p: p[0], pairs) # Custom
xcoords = [0, 5, ...] # (or iterable)
我也问因为Haskell确实有这样的功能Data.List.head ,作为高阶函数的参数很有用:
head :: [a] -> a
head (x:xs) = x
head xs = xs !! 0
xcoords = (map head) pairs
最佳答案
您需要使用 operator.itemgetter
>>> import operator
>>> pairs = [(0,1), (5,3)]
>>> xcoords = map(operator.itemgetter(0), pairs)
>>> xcoords
[0, 5]
在 Python3 中,map
返回一个 map 对象,因此您需要一个 list
调用它。
>>> list(map(operator.itemgetter(0), pairs))
[0, 5]
关于返回索引 0 处的值的 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373923/