简体   繁体   English

将列表中的每个元素转换为单独的字符串?

[英]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. 在这里面,每个元素是一个列表本身,除了-9999值其是int的值。

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. 假设我要使用for循环将每个元素转换为string ,以便将其写入excelcsv文件。 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 . map将函数应用于myList每个元素。 Using the str function will transform each element in your list in a string so you can use it freely. 使用str函数可以将列表中的每个元素转换为字符串,因此您可以自由使用它。

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. 首先,在每次迭代中,您都使用str.join从完整列表中生成一个字符串,而您只需要str(elem) ,其中elem是列表中的当前项目。

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 enumerate is used to get the index value alongside each item of a list. enumerate用于获取列表中每个项目旁边的索引值。 Your original code took the index and the item both as i . 您的原始代码将索引和项目都视为i ie. 即。 i = (0, [3, 95]) , when really you'd want them separate. i = (0, [3, 95]) ,实际上您希望它们分开。 If you need these indices, use this: 如果您需要这些索引,请使用此:

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

Where i = 0 and elem = [3, 95] . 其中i = 0elem = [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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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