简体   繁体   中英

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

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.

You've made two separate mistakes here. First, inside each iteration you're using str.join which makes a string from the full list, when you just want str(elem) where elem is the current item in the list.

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

You also used enumerate improperly. enumerate is used to get the index value alongside each item of a list. Your original code took the index and the item both as i . ie. i = (0, [3, 95]) , when really you'd want them separate. If you need these indices, use this:

for i, elem in enumerate(mylist):
    str1 = str(elem)

Where i = 0 and elem = [3, 95] .

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

# convert all elements
new_list = [str(e) for e in mylist ]

# use it
for str1 in new_list:
    print str1

or

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

for x in mylist:
    # convert one element and use it
    str1 = str(x) 
    print str1

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