Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从字符串中创建列表_Python_String_List_Python 2.7 - Fatal编程技术网

Python 如何从字符串中创建列表

Python 如何从字符串中创建列表,python,string,list,python-2.7,Python,String,List,Python 2.7,有没有办法从字符串生成: "I like Python!!!" 像这样的清单 ['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!'] 使用: 而且 输出: ['I', ' ', 'l', 'i', 'k', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!'] 速度比较: $ python -m timeit 'list("I like Python

有没有办法从字符串生成:

"I like Python!!!"
像这样的清单

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

而且

输出:

['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

并不是说这比其他的好。。。但是理解很有趣

[x for x in 'I like Python']

看起来结果列表中不需要任何空格,请尝试:

>>> 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

它的速度更快,但不起作用,它只会在空间Delimeters上分裂。所以它确实如此,你是对的。删除该选项,将列表理解添加到速度比较中。到目前为止,只有正确答案+1表示字符串可以像列表一样使用。。你的最后4个问题在标题的开头有“Python2.7:”。为什么我要投反对票?
>>> 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