Python函数返回索引0处的值?

Nay*_*uki 7 python lambda dictionary list

Python标准库是否具有返回索引0处的值的函数?换一种说法:

zeroth = lambda x: x[0]
Run Code Online (Sandbox Code Playgroud)

我需要在高阶函数中使用它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)
Run Code Online (Sandbox Code Playgroud)

我也问,因为Haskell确实有一个函数Data.List.head,它可以用作高阶函数的参数:

head :: [a] -> a
head (x:xs) = x
head xs = xs !! 0

xcoords = (map head) pairs
Run Code Online (Sandbox Code Playgroud)

Bha*_*Rao 6

你需要使用 operator.itemgetter

>>> import operator
>>> pairs = [(0,1), (5,3)]
>>> xcoords = map(operator.itemgetter(0), pairs)
>>> xcoords
[0, 5]
Run Code Online (Sandbox Code Playgroud)

在Python3中,map返回一个map对象,因此你需要list对它进行调用.

>>> list(map(operator.itemgetter(0), pairs))
[0, 5]
Run Code Online (Sandbox Code Playgroud)

  • FWIW,我发现`lambda p:p [0]`比`operator.itemgetter(0)更清晰` (2认同)
  • @BhargavRao,itemgetter比lambda快,所以绝对不是性能 (2认同)