Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn each element of a list into a separate string?

I have the following list:

mylist=[[3, 95],[8, 92],[18, 25],[75, 78],[71, 84],-9999,[96, 50],[91, 70],-9999,[19, 60]]

In it, each element is a list itself, apart from the -9999 values which are int values.

Say that I want to use a for loop to transform each element into a string, in order to write it to an excel or csv file. How could I do it?

Here is my attempt:

mylist=[[3, 95],[8, 92],[18, 25],[75, 78],[71, 84],-9999,[96, 50],[91, 70],-9999,[19, 60]]
for i in enumerate(mylist):
    str1 = ''.join(str(e) for e in mylist)

But what I get is the entire list transformed into a single string, without each item being differentiated:

str1='[3, 95][8, 92][18, 25][75, 78][71, 84]-9999[96, 50][91, 70]-9999[19, 60]'

Instead, I would like this:

str1='[3,95]' #Iter 1
str1='[8, 92]' #Iter 2
str1='[18, 25]' #Iter 3
...
#and so forth
like image 265
FaCoffee Avatar asked Sep 13 '25 15:09

FaCoffee


1 Answers

This should work:

for e in map(str, myList):
    #do your stuff here, e is '[3, 95]' on the fst element and so on

map applies a function to each element in myList. Using the str function will transform each element in your list in a string so you can use it freely.

like image 185
Netwave Avatar answered Sep 16 '25 07:09

Netwave