我如何使用带有 lambda 的 map 函数将下面的列表从摄氏度转换为华氏度?
How would I Convert the list below from Celsius to Fahrenheit, using the map function with a lambda?
我一直很难尝试转换此列表,因为它内部有一个元组并且操作元组并不容易,因为它们本质上是不可更改的。但显然有办法解决它,因为我能够调整数字,但是我无法带回一个字符串来制作一个新列表。我在尝试时收到此错误:
Traceback (most recent call last):
File "/Users/Swisha/Documents/Coding Temple/Python VI/tupe.py", line 4, in <module>
newplaces = list(map(lambda c: c[0] (9/5) * c[1]+ 32, places))
File "/Users/Swisha/Documents/Coding Temple/Python VI/tupe.py", line 4, in <lambda>
newplaces = list(map(lambda c: c[0] (9/5) * c[1]+ 32, places))
TypeError: 'str' object is not callable
我的错误尝试:
# F = (9/5)*C + 32
places = [('Nashua',32),("Boston",12),("Los Angelos",44),("Miami",29)]
newplaces = list(map(lambda c: c[0] (9/5) * c[1]+ 32, places))
print(newplaces)
我没有字符串的输出:
[89.6, 53.6, 111.2, 84.2]
要求的输出:
[('Nashua', 89.6), ('Boston', 53.6), ('Los Angelos', 111.2), ('Miami', 84.2)]
c
是元组(c[0]
是地名),所以
# return a tuple that includes the place name
newplaces = list(map(lambda c: (c[0], (9/5) * c[1]+ 32), places))
print(newplaces)
[('Nashua', 89.6), ('Boston', 53.6), ('Los Angelos', 111.2), ('Miami', 84.2)]
您还应该包括元组的第一个元素。
places = [('Nashua',32),("Boston",12),("Los Angelos",44), ("Miami",29)]
newplaces = list(map(lambda c: (c[0], (9/5) * c[1]+ 32), places))
print(newplaces)
我建议使用列表理解,而不是函数式map()
,如果不是学习目的,可读性差。
# F = (9/5)*C + 32
places = [('Nashua',32),("Boston",12),("Los Angelos",44),("Miami",29)]
newplaces = [(place, (9/5) * c + 32) for place, c in places]
print(newplaces)
我一直很难尝试转换此列表,因为它内部有一个元组并且操作元组并不容易,因为它们本质上是不可更改的。但显然有办法解决它,因为我能够调整数字,但是我无法带回一个字符串来制作一个新列表。我在尝试时收到此错误:
Traceback (most recent call last):
File "/Users/Swisha/Documents/Coding Temple/Python VI/tupe.py", line 4, in <module>
newplaces = list(map(lambda c: c[0] (9/5) * c[1]+ 32, places))
File "/Users/Swisha/Documents/Coding Temple/Python VI/tupe.py", line 4, in <lambda>
newplaces = list(map(lambda c: c[0] (9/5) * c[1]+ 32, places))
TypeError: 'str' object is not callable
我的错误尝试:
# F = (9/5)*C + 32
places = [('Nashua',32),("Boston",12),("Los Angelos",44),("Miami",29)]
newplaces = list(map(lambda c: c[0] (9/5) * c[1]+ 32, places))
print(newplaces)
我没有字符串的输出:
[89.6, 53.6, 111.2, 84.2]
要求的输出:
[('Nashua', 89.6), ('Boston', 53.6), ('Los Angelos', 111.2), ('Miami', 84.2)]
c
是元组(c[0]
是地名),所以
# return a tuple that includes the place name
newplaces = list(map(lambda c: (c[0], (9/5) * c[1]+ 32), places))
print(newplaces)
[('Nashua', 89.6), ('Boston', 53.6), ('Los Angelos', 111.2), ('Miami', 84.2)]
您还应该包括元组的第一个元素。
places = [('Nashua',32),("Boston",12),("Los Angelos",44), ("Miami",29)]
newplaces = list(map(lambda c: (c[0], (9/5) * c[1]+ 32), places))
print(newplaces)
我建议使用列表理解,而不是函数式map()
,如果不是学习目的,可读性差。
# F = (9/5)*C + 32
places = [('Nashua',32),("Boston",12),("Los Angelos",44),("Miami",29)]
newplaces = [(place, (9/5) * c + 32) for place, c in places]
print(newplaces)