我正在使用 Python 3。我正在尝试编写一个 lambda 函数/表达式 并生成一个字符串类型的输出。我不确定在这个问题上我不理解什么。
Cel = [39.5, 36.5, 37.3, 37.8]
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
print(Fer)
打印:
<function <lambda> at 0x7fafc369eea0>
但是,我希望值列表为:
[103.1, 97.70, 99.14, 100.03]
然后我尝试用 lambda 映射
Fer2 = map(lambda x: (float(9)/5)*x + 32, Cel)
print(Fer2) # prints:
<map object at 0x7fafc36b5b38> # still no success
for x in Fer:
print(x) # this doesn't work and gives following error
TypeError: 'function' object is not iterable
for x in Fer2:
print(x) # but this works and prints
103.10
97.7
99.14
100.039
为什么我不能简单地将 print(Fer or Fer2) 作为值列表获取,例如: [103.1, 97.70, 99.14, 100.03]
如何在 lambda 中解决这个问题,而无需编写另一个 def 函数?
请您参考如下方法:
不太清楚为什么你需要 lambda 这是一个简单的列表理解
Fer = [32+float(9)/5*x for x in Cel]
或者如果你想使用 lambda,你将不得不使用 map
Fer = list(map(lambda x: (float(9)/5*x + 32),Cel))
由于您正在遍历 Fer,因此您可以省略 list
Fer = map(lambda x: (float(9)/5*x + 32),Cel)
您当前的尝试基本上是尝试混合映射和列表理解。更详细地说,您对下一行代码所做的是创建一个 lambda 函数并将其分配给一个名为 Fer 的变量,这不是您想要的。
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
