如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
当前回答
您也可以在列表操作中使用extend方法。
>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
其他回答
下面是一个很好的脚本,可以帮助你找到最有效的方法:
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")
使用列表构造函数:
>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']
List使用通过迭代输入iterable获得的项构建一个新列表。字符串是一个可迭代对象——在每个迭代步骤中迭代它会产生一个单独的字符。
你也可以用这种非常简单的方式来做,没有list():
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
解压缩:
word = "Paralelepipedo"
print([*word])
如果你想一次处理一个字符串字符。你有多种选择。
uhello = u'Hello\u0020World'
使用列表推导式:
print([x for x in uhello])
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
使用地图:
print(list(map(lambda c2: c2, uhello)))
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
调用内置列表函数:
print(list(uhello))
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
使用for循环:
for c in uhello:
print(c)
输出:
H
e
l
l
o
W
o
r
l
d