如何在Python中将带有逗号分隔的项目的字符串转换为列表?

问题:如何在Python中将带有逗号分隔的项目的字符串转换为列表?

如何将字符串转换为列表?

说的字符串就像text = "a,b,c"。转换后,text == ['a', 'b', 'c']希望是text[0] == 'a'text[1] == 'b'

How do you convert a string into a list?

Say the string is like text = "a,b,c". After the conversion, text == ['a', 'b', 'c'] and hopefully text[0] == 'a', text[1] == 'b'?


回答 0

像这样:

>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]

另外,eval()如果您信任字符串是安全的,则可以使用:

>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')

Like this:

>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]

Alternatively, you can use eval() if you trust the string to be safe:

>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')

回答 1

只是补充现有的答案:希望将来您会遇到更多类似的情况:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

但是,你正在处理什么用,现在,一起去@ 卡梅隆的回答。

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'

Just to add on to the existing answers: hopefully, you’ll encounter something more like this in the future:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

But what you’re dealing with right now, go with @Cameron‘s answer.

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'

回答 2

以下Python代码会将您的字符串转换为字符串列表:

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)

The following Python code will turn your string into a list of strings:

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)

回答 3

我不认为你需要

在python中,您几乎不需要将字符串转换为列表,因为字符串和列表非常相似

改变类型

如果您确实有一个应该是字符数组的字符串,请执行以下操作:

In [1]: x = "foobar"
In [2]: list(x)
Out[2]: ['f', 'o', 'o', 'b', 'a', 'r']

不更改类型

请注意,字符串非常类似于python中的列表

字符串具有访问器,例如列表

In [3]: x[0]
Out[3]: 'f'

字符串是可迭代的,例如列表

In [4]: for i in range(len(x)):
...:     print x[i]
...:     
f
o
o
b
a
r

TLDR

字符串是列表。几乎。

I don’t think you need to

In python you seldom need to convert a string to a list, because strings and lists are very similar

Changing the type

If you really have a string which should be a character array, do this:

In [1]: x = "foobar"
In [2]: list(x)
Out[2]: ['f', 'o', 'o', 'b', 'a', 'r']

Not changing the type

Note that Strings are very much like lists in python

Strings have accessors, like lists

In [3]: x[0]
Out[3]: 'f'

Strings are iterable, like lists

In [4]: for i in range(len(x)):
...:     print x[i]
...:     
f
o
o
b
a
r

TLDR

Strings are lists. Almost.


回答 4

如果要按空格分割,可以使用.split()

a = 'mary had a little lamb'
z = a.split()
print z

输出:

['mary', 'had', 'a', 'little', 'lamb'] 

In case you want to split by spaces, you can just use .split():

a = 'mary had a little lamb'
z = a.split()
print z

Output:

['mary', 'had', 'a', 'little', 'lamb'] 

回答 5

如果您实际上想要数组:

>>> from array import array
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> myarray = array('c', text)
>>> myarray
array('c', 'abc')
>>> myarray[0]
'a'
>>> myarray[1]
'b'

如果您不需要数组,只想按索引查看您的字符,请记住字符串是可迭代的,就像列表一样,除了它是不可变的:

>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> text[0]
'a'

If you actually want arrays:

>>> from array import array
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> myarray = array('c', text)
>>> myarray
array('c', 'abc')
>>> myarray[0]
'a'
>>> myarray[1]
'b'

If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:

>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> text[0]
'a'

回答 6

m = '[[1,2,3],[4,5,6],[7,8,9]]'

m= eval(m.split()[0])

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
m = '[[1,2,3],[4,5,6],[7,8,9]]'

m= eval(m.split()[0])

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

回答 7

所有答案都很好,还有另一种方法,即列表理解,请参见下面的解决方案。

u = "UUUDDD"

lst = [x for x in u]

对于逗号分隔的列表,请执行以下操作

u = "U,U,U,D,D,D"

lst = [x for x in u.split(',')]

All answers are good, there is another way of doing, which is list comprehension, see the solution below.

u = "UUUDDD"

lst = [x for x in u]

for comma separated list do the following

u = "U,U,U,D,D,D"

lst = [x for x in u.split(',')]

回答 8

我通常使用:

l = [ word.strip() for word in text.split(',') ]

strip删除单词周围的空格。

I usually use:

l = [ word.strip() for word in text.split(',') ]

the strip remove spaces around words.


回答 9

要转换string具有a="[[1, 3], [2, -6]]"我编写但尚未优化的代码的形式:

matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
    row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
    matrixAr.append(row)
print matrixAr

To convert a string having the form a="[[1, 3], [2, -6]]" I wrote yet not optimized code:

matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
    row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
    matrixAr.append(row)
print matrixAr

回答 10

# to strip `,` and `.` from a string ->

>>> 'a,b,c.'.translate(None, ',.')
'abc'

您应该translate对字符串使用内置方法。

help('abc'.translate)在Python shell上键入以获取更多信息。

# to strip `,` and `.` from a string ->

>>> 'a,b,c.'.translate(None, ',.')
'abc'

You should use the built-in translate method for strings.

Type help('abc'.translate) at Python shell for more info.


回答 11

使用功能性Python:

text=filter(lambda x:x!=',',map(str,text))

Using functional Python:

text=filter(lambda x:x!=',',map(str,text))

回答 12

例子1

>>> email= "myemailid@gmail.com"
>>> email.split()
#OUTPUT
["myemailid@gmail.com"]

例子2

>>> email= "myemailid@gmail.com, someonsemailid@gmail.com"
>>> email.split(',')
#OUTPUT
["myemailid@gmail.com", "someonsemailid@gmail.com"]

Example 1

>>> email= "myemailid@gmail.com"
>>> email.split()
#OUTPUT
["myemailid@gmail.com"]

Example 2

>>> email= "myemailid@gmail.com, someonsemailid@gmail.com"
>>> email.split(',')
#OUTPUT
["myemailid@gmail.com", "someonsemailid@gmail.com"]