简体   繁体   中英

split elements in a list

I'm trying to split the elements in some lists but I can only get each character

example: split those lists

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

with this code

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

I get this result:

[['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']]

I'd like to get

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

What did I miss here? Thanks

Why don't you use something like

>>> a = [999.7382621, -1.4637250000000002]
>>> map(lambda x: [str(x)], a)
[['999.7382621'], ['-1.463725']]
>>> 

Why do you want to use split?

if your original data are lines of a text file:

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]]

Looks like mylists variable is a single string and when you say

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

you actually iterating not over lines but over characters. Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM