gpt4 book ai didi

python - 将函数映射到元组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:55 24 4
gpt4 key购买 nike

我想到了一些我会在 Haskell 中做的事情:

f :: Int -> (Int, Int)
-- for example:
f = `divMod` 12
foo :: [Int] -> (Int, Int)
foo = map (fmap (+1) . f)
-- foo [10, 11, 12, 13] = [(0,11),(0,12),(1,1),(1,2)]

是否有可能在 Python 中优雅地进行元组映射(无需查看 f 内部?)我能想到的最好的是:

def foo(lst):
for x in lst:
a, b = f(x)
yield a, b + 1

另一种可能是

def foo(lst):
return map(lambda x: (f(x)[0], f(x)[1]+1), lst)

但我不喜欢这两种解决方案。我不喜欢第一个,因为它不是一个单一的表达式,不能那么容易地内联。另一个解决方案具有此属性,但它很丑陋,因为它在每次迭代中不必要地调用 f() 两次。是否有可能以某种方式在迭代中解压结果?

最佳答案

首先将lst映射到f:

try:
# Python 2, forward compatible version of map
from future_builtins import map
except ImportError:
# Python 3, map is already an iterator
pass

def foo(lst):
return [(fxa, fxb + 1) for fxa, fxb in map(f, lst)]
# or a generator expression for lazy evaluation
# return ((fxa, fxb + 1) for fxa, fxb in map(f, lst))

关于python - 将函数映射到元组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43249618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com