拆分列表中的元素

时间:2016-05-04 21:03:25

标签: python python-2.7

我试图在某些列表中拆分元素,但我只能得到每个字符

例如: 拆分这些列表

[999.7382621, -1.4637250000000002]
[-1.5490111999999998, 1.5490111999999998]

使用此代码

elements = [map(str, line.split(",")) for line in mylists]

我得到了这个结果:

[['9'], ['9'], ['9'], ['.'], ['7'], ['3'], ['8'], ['2'], ['6'], ['2'], ['1'],['', ''], ['-'], ['1'], ['.'], ['4'], ['6'], ['3'], ['7'], ['2'], ['5']]
[['-'], ['1'], ['.'], ['5'], ['4'], ['9'], ['0'], ['1'], ['1'], ['2'], ['', ''], ['1'], ['.'], ['5'], ['4'], ['9'], ['0'], ['1'], ['1'], ['2']]

我想

[['999.7382621'],['-1.4637250000000002']]
[['-1.5490111999999998'],['1.5490111999999998']]

我在这里想念什么?感谢

3 个答案:

答案 0 :(得分:0)

为什么不使用

之类的东西
>>> a = [999.7382621, -1.4637250000000002]
>>> map(lambda x: [str(x)], a)
[['999.7382621'], ['-1.463725']]
>>> 

为什么要使用拆分?

答案 1 :(得分:0)

如果您的原始数据是文本文件的行:

In [135]: line = '[999.7382621, -1.4637250000000002]'

In [136]: import ast

In [137]: ast.literal_eval(line)
Out[137]: [999.7382621, -1.4637250000000002]

In [138]: [[x] for x in ast.literal_eval(line)]
Out[138]: [[999.7382621], [-1.4637250000000002]]

答案 2 :(得分:0)

看起来mylists变量是单个字符串,当你说

elements = [map(str, line.split(",")) for line in mylists]

你实际上不是通过线而是通过字符迭代。尝试:

elements = [map(str, line.split(",")) for line in mylists.strip('\n').split('\n')]