0

I have a nested list named value, and I need to convert all things inside into string type and join them together.

This is currently how I do it:

value=[['2014-11-20 10:51:50', 7.36, 7.63, 0.4487, 12.37, 10.4, 39.85, 52.27, 0.41, 0.78, 6], 
       ['2014-11-20 11:22:07', 7.41, 7.67, 0.4489, 12.44, 6.6, 40.39, 53.98, 0.41, 0.754, 6]]

for i, n in enumerate(value):
    for j, m in enumerate(value[i]):
         value[i][j]=str(value[i][j])
    ",".join(value[i]) 

As I am new to Python, I would like to know is there a better or faster way to do it. Or maybe there is some built in functions that could do the job?

Choon Lim
  • 3
  • 2

1 Answers1

1
value = [ ",".join(map(str,i)) for i in value ]

map will convert all float type to str and then join will join them

if you didn't understand about map how it working:

value = [ ",".join(str(x) for x in i) for i in value ]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • Thanks. That is very clear to understand. I have read somewhere that map is not as fast as list comprehension in most of cases. In this case, which way is faster? – Choon Lim Nov 20 '14 at 06:05
  • it depends check here, its answered here,http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map. but in ur case map will be faster – Hackaholic Nov 20 '14 at 06:08