我有包含字符串值的列表列表:
List = [['138.314038', '-35.451642'],
['138.313946', '-35.45212'],
['138.313395', '-35.45291'],
['138.312425', '-35.453978'],
['138.311697', '-35.454879'],
['138.311042', '-35.45569'],
['138.310407', '-35.45647'],
['138.315603', '-35.44981'],
['138.315178', '-35.450241'],
['138.314603', '-35.450948'],
['138.314038', '-35.45164']]
我正在尝试将列表列表中的每个字符串值转换为浮点值。
我正在尝试:
results = [float(i) for i in List]
但是我只索引列表,而不索引其中的值。如何使用类似的方法并保持变量List的结构相同。
答案 0 :(得分:4)
您有列表,因此请使用双重理解:
results = [[float(i) for i in e] for e in List]
答案 1 :(得分:3)
我正在使用numpy
进行转换
np.array(List).astype(float).tolist()
Out[185]:
[[138.314038, -35.451642],
[138.313946, -35.45212],
[138.313395, -35.45291],
[138.312425, -35.453978],
[138.311697, -35.454879],
[138.311042, -35.45569],
[138.310407, -35.45647],
[138.315603, -35.44981],
[138.315178, -35.450241],
[138.314603, -35.450948],
[138.314038, -35.45164]]
答案 2 :(得分:2)
使用两个list
map
可能很丑:
print(list(map(lambda x: list(map(float,x)), List)))
输出:
[[138.314038, -35.451642], [138.313946, -35.45212], [138.313395, -35.45291], [138.312425, -35.453978], [138.311697, -35.454879], [138.311042, -35.45569], [138.310407, -35.45647], [138.315603, -35.44981], [138.315178, -35.450241], [138.314603, -35.450948], [138.314038, -35.45164]]
更好地打印:
pprint.pprint(list(map(lambda x: list(map(float,x)), List)))
输出:
[[138.314038, -35.451642],
[138.313946, -35.45212],
[138.313395, -35.45291],
[138.312425, -35.453978],
[138.311697, -35.454879],
[138.311042, -35.45569],
[138.310407, -35.45647],
[138.315603, -35.44981],
[138.315178, -35.450241],
[138.314603, -35.450948],
[138.314038, -35.45164]]
答案 3 :(得分:2)
#you can use map function as well
results = [list(map(float,x)) for x in List]
答案 4 :(得分:1)
您可以像这样展开列表:
results = [list(map(float, l)) for l in List]
答案 5 :(得分:1)
您可以使用地图来实现。
floats = [ list(map(float, i)) for i in List ]