我一直在努力转换这个列表,因为它里面有一个元组,操作元组并不容易,因为本质上它们是不可更改的。但显然有办法绕过它,因为我能够调整数字,但是我不能带回一个字符串,以及使一个新的列表。当我尝试
时,我收到这个错误: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)