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

标签 python list dictionary lambda

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/

相关文章:

python - 从列表中获取元素,循环方式

python - 排序/过滤/求和列表中递增数字的最快方法是什么

swift - Dictionary 类型的计算属性的 Setter

python - 准备用于生产的 Pyramid 应用程序

python - 在两个 BeautifulSoup 元素之间拉出文本

python - 为什么我的小数点四舍五入到一位有效数字?

python - IndentationError : unexpected indent Python 3 Error [duplicate]

python - 有没有办法管理列表中的 float ?

python - 使用 Single Pass 算法将数据帧中通过 for 循环生成的列表与具有字典值的列表相交的快速方法

c# - ContainsKey线程安全