如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
当前回答
好吧,尽管我很喜欢列表的版本,这里是我发现的另一种更详细的方法(但它很酷,所以我想我将它添加到争论中):
>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']
其他回答
如果你只需要一个字符数组:
arr = list(str)
如果你想用一个特定的分隔符分隔str:
# str = "temp//temps" will will be ['temp', 'temps']
arr = str.split("//")
要分割字符串s,最简单的方法是将其传递给list()。所以,
s = 'abc'
s_l = list(s) # s_l is now ['a', 'b', 'c']
你也可以使用列表推导式,这是可行的,但不像上面那样简洁:
s_l = [c for c in s]
当然还有其他方法,但这些方法就足够了。 之后,如果你想重新组合它们,简单地调用"".join(s_l)将使你的列表恢复到以前的字符串形式…
将字符串传递给list()
s = "mystring"
l = list(s)
print l
好吧,尽管我很喜欢列表的版本,这里是我发现的另一种更详细的方法(但它很酷,所以我想我将它添加到争论中):
>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']
下面是一个很好的脚本,可以帮助你找到最有效的方法:
import timeit
from itertools import chain
string = "thisisthestringthatwewanttosplitintoalist"
def getCharList(str):
return list(str)
def getCharListComp(str):
return [char for char in str]
def getCharListMap(str):
return list(map(lambda c: c, str))
def getCharListForLoop(str):
list = []
for c in str:
list.append(c)
def getCharListUnpack(str):
return [*str]
def getCharListExtend(str):
list = []
return list.extend(str)
def getCharListChain(str):
return chain(str)
time_list = timeit.timeit(stmt='getCharList(string)', globals=globals(), number=1)
time_listcomp = timeit.timeit(stmt='getCharListComp(string)', globals=globals(), number=1)
time_listmap = timeit.timeit(stmt='getCharListMap(string)', globals=globals(), number=1)
time_listforloop = timeit.timeit(stmt='getCharListForLoop(string)', globals=globals(), number=1)
time_listunpack = timeit.timeit(stmt='getCharListUnpack(string)', globals=globals(), number=1)
time_listextend = timeit.timeit(stmt='getCharListExtend(string)', globals=globals(), number=1)
time_listchain = timeit.timeit(stmt='getCharListChain(string)', globals=globals(), number=1)
print(f"Execution time using list constructor is {time_list} seconds")
print(f"Execution time using list comprehension is {time_listcomp} seconds")
print(f"Execution time using map is {time_listmap} seconds")
print(f"Execution time using for loop is {time_listforloop} seconds")
print(f"Execution time using unpacking is {time_listunpack} seconds")
print(f"Execution time using extend is {time_listextend} seconds")
print(f"Execution time using chain is {time_listchain} seconds")