如何从字符串中创建列表

时间:2013-08-15 16:04:09

标签: python string list python-2.7

有没有办法从字符串:

"I like Python!!!"

这样的列表
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']

4 个答案:

答案 0 :(得分:13)

使用list comprehension

>>> mystr = "I like Python!!!"
>>> [c for c in mystr if c != " "]
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
>>> [c for c in mystr if not c.isspace()] # alternately
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
>>>

答案 1 :(得分:6)

看起来您不希望结果列表中有任何空格,请尝试:

>>> s = "I like Python!!!"
>>> list(s.replace(' ',''))
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']

但你确定你需要一个清单吗?请记住,在大多数情况下,字符串可以像列表一样对待:它们是序列,可以迭代,许多接受列表的函数也接受字符串。

>>> for c in ['a','b','c']:
...     print c
... 
a
b
c
>>> for c in 'abc':
...     print c
... 
a
b
c

答案 2 :(得分:1)

此外,

list("I like Python!!!")

输出:

['I', ' ', 'l', 'i', 'k', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']

速度比较:

$ python -m timeit 'list("I like Python!!!")'
1000000 loops, best of 3: 0.783 usec per loop
$ python -m timeit '[x for x in "I like Python!!!"]'
1000000 loops, best of 3: 1.79 usec per loop

答案 3 :(得分:1)

这并不比其他人好......但理解很有趣!

[x for x in 'I like Python']