将字符串拆分为浮点列表

时间:2017-03-14 20:52:31

标签: python string split

我有一个看起来像这样的字符串:

'-300.0,120.0; -186.0,120.0; -106.0,80.0; -78.0,55.0; -57.0,40.0; -29.0,15.0; -10.0,15.0; 10.0,-11.0; 19.0,-11.0; 28.0,-12.0; 57.0,-27.5; 78.0,-37.0; 106.0,-50.0; 150.0,-70.0; 186.0,-90.0; 236.0,-110.0; 300.0,-120.0'

我想做一个散点图,在列之前的X轴编号和列之后的Y轴编号上。每对由';'。

分隔

我在列表中有很多这样的字符串,所以我不能使用read_csv或类似的函数。

有没有办法将其格式化为元组列表?还是2个列表?

由于

2 个答案:

答案 0 :(得分:3)

是的,单行。根据{{​​1}}拆分,然后迭代这些字符串,并拆分/转换为float,例如强制迭代;

tuple

或使用s = '-300.0,120.0; -186.0,120.0; -106.0,80.0; -78.0,55.0; -57.0,40.0; -29.0,15.0; -10.0,15.0; 10.0,-11.0; 19.0,-11.0; 28.0,-12.0; 57.0,-27.5; 78.0,-37.0; 106.0,-50.0; 150.0,-70.0; 186.0,-90.0; 236.0,-110.0; 300.0,-120.0' tuples = [tuple(float(y) for y in x.split(",")) for x in s.split(";")] print(tuples) ,稍快一些,并且因为强制迭代到map而在python 3上工作:

tuple

结果:

tuples = [tuple(map(float,x.split(","))) for x in s.split(";")]

答案 1 :(得分:0)

为完成而添加绘图部分:

import matplotlib.pyplot as plt

s = '-300.0,120.0; -186.0,120.0; -106.0,80.0; -78.0,55.0; ' \
    '-57.0,40.0; -29.0,15.0; -10.0,15.0; 10.0,-11.0; 19.0,-11.0; ' \
    '28.0,-12.0; 57.0,-27.5; 78.0,-37.0; 106.0,-50.0; 150.0,-70.0; ' \
    '186.0,-90.0; 236.0,-110.0; 300.0,-120.0'

v = [tuple(map(float, t.split(","))) for t in s.split("; ")]

plt.scatter(*zip(*v))
plt.show()

获得两个单独的序列:

x, y = zip(*v)

plt.scatter(x, y)
plt.show()

或者:

x = [w[0] for w in v]
y = [w[1] for w in v]

plt.scatter(x, y)
plt.show()

或者:

x = [a for a, b in v]
y = [b for a, b in v]

plt.scatter(x, y)
plt.show()