我正在寻找一个字符串并创建一个构建原始字符串的字符串列表.
例如:
"asdf" => ["a", "as", "asd", "asdf"]
Run Code Online (Sandbox Code Playgroud)
我确信有一种"pythonic"方式可以做到这一点; 我想我只是在失去理智.完成这项工作的最佳方法是什么?
dF.*_*dF. 19
一种可能性:
>>> st = 'asdf'
>>> [st[:n+1] for n in range(len(st))]
['a', 'as', 'asd', 'asdf']
Run Code Online (Sandbox Code Playgroud)
Ben*_*ank 17
如果你要循环遍历"列表"的元素,你可能最好使用生成器而不是列表理解:
>>> text = "I'm a little teapot."
>>> textgen = (text[:i + 1] for i in xrange(len(text)))
>>> textgen
<generator object <genexpr> at 0x0119BDA0>
>>> for item in textgen:
... if re.search("t$", item):
... print item
I'm a lit
I'm a litt
I'm a little t
I'm a little teapot
>>>
Run Code Online (Sandbox Code Playgroud)
此代码永远不会创建列表对象,也不会(delta垃圾收集)创建多个额外字符串(除此之外text).