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发布于 2015-12-19 18:24:04
您需要使用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]发布于 2015-12-19 18:24:41
最重要的Pythonic方法可能使用operator.itemgetter(0)。它只返回这样一个函数。
另一种方法是直接调用obj.__getitem__。它不那么Pythonic,因为它显式地调用特殊的方法名称,而不是允许Python推断内部调用什么。
发布于 2015-12-19 18:26:48
有一个列表理解
>>> pairs = [(0,1), (5,3)]
>>> xcoords = [ t[0] for t in pairs ]
>>> xcoordshttps://stackoverflow.com/questions/34373923
复制相似问题