在以前的Python版本中,可以通过调用locals()[' _ [1]']来获取列表推导中列表的引用。因为它似乎不再起作用,还有另一种方法可以获得它吗?
例如,在下面的代码中,我想使用mul函数的结果作为add函数的参数(即我想将最后一个值添加到dict中)。
mul = lambda a,b: a*b
add = lambda a,b: a+b
res = {f:f(*args) for f, args in [(mul,[4,5]), (add,[2,9])]}
修改 请关注这个问题,而不仅仅是其中一个例子......
答案 0 :(得分:1)
我不确定如何在列表理解中获取列表中的引用。
但是你提到想要使用理解来使用你的mul函数的结果作为你的add函数的一部分。这是一个列表理解,这样做。 (添加,[值])+(mul [值])
python3.4
mul = lambda a,b: a*b
add = lambda a,b: a+b
res = {f:f(*args) for f, args in [(mul,[4,5]), (add,[2,9])]}
a = [(mul,[4,5]), (mul,[2,9]), (mul, [14,29])]
b = [(add,[2, 0]), (add,[10, 20]), (add,[20, 15])]
c = list(zip(a, b))
更容易阅读for循环:
for i in c:
a = i[0][0](*i[0][1]) # a = mul(*args)
b = i[1][0](i[1][0](*i[1][1]), a) # b = add(add(*args), mul(*args))
print(b)
22 48 441
作为列表理解:
a_list = [i[1][0](i[1][0](*i[1][1]), i[0][0](*i[0][1]))for i in c]
print(a_list)
[22,48,441]
答案 1 :(得分:1)
这是你想要的,但在词典理解中?
In [79]: result=[]
In [80]: for f, args in [(add,[4,5]), (mul,[2])]:
if len(args)==1:
args.append(result[-1][-1])
result.append([f,f(*args)])
In [81]: result
Out[81]: [[<function __main__.<lambda>>, 9],
[<function __main__.<lambda>>, 18]]
如果输入列表是:
[(mul,[4,5]), (add,[2])]
结果将是:
[[<function __main__.<lambda>>, 20], [<function __main__.<lambda>>, 22]
我使用了列表而不是字典,因为更容易指定&#39;使用上次计算的结果&#39;。我在第一种情况下切换了函数,因为add(4,5)
产生9
,这是第二种情况的参数之一。
在任何情况下,您都希望以某种方式访问result
,并在当前计算中使用其中的值。 reduce
具有这种行为,保持当前state
作为其中一个输入功能。 numpy
有cumsum
(和cumprod
),它们也会收集这些中间值。
你如何在早期的Python(前2.7?)中编写这个列表理解,res
命名空间中locals()
可用?那将是字典理解之前,对吗?
如何将中间结果保存在自己的变量中?
In [95]: def g(f,arg):
x = f(tempval[0],arg)
tempval[0]=x
return x
In [96]: tempval=[5]
In [97]: [g(f,arg) for f,arg in [(add,4),(mul,2)]]
Out[97]: [9, 18]