如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
使用列表构造函数:
>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']
List使用通过迭代输入iterable获得的项构建一个新列表。字符串是一个可迭代对象——在每个迭代步骤中迭代它会产生一个单独的字符。
如果希望只读访问字符串,可以直接使用数组表示法。
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t = 'my string'
>>> t[1]
'y'
对于不使用regexp的测试可能很有用。 字符串是否包含结束换行符?
>>> t[-1] == '\n'
False
>>> t = 'my string\n'
>>> t[-1] == '\n'
True
我探索了另外两种方法来完成这项任务。它可能对某人有帮助。
第一个很简单:
In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
第二个使用map和函数。它可能适用于更复杂的任务:
In [36]: s = 'foobar12'
In [37]: a = map(lambda c: c, s)
In [38]: a
Out[38]: ['f', 'o', 'o', 'b', 'a', 'r', '1', '2']
例如
# isdigit, isspace or another facilities such as regexp may be used
In [40]: a = map(lambda c: c if c.isalpha() else '', s)
In [41]: a
Out[41]: ['f', 'o', 'o', 'b', 'a', 'r', '', '']
有关更多方法,请参阅python文档
好吧,尽管我很喜欢列表的版本,这里是我发现的另一种更详细的方法(但它很酷,所以我想我将它添加到争论中):
>>> 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']
你也可以用这种非常简单的方式来做,没有list():
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
这个任务可以归结为遍历字符串中的字符并将它们收集到一个列表中。最naïve的解决方案是这样的
result = []
for character in string:
result.append(character)
当然,也可以缩写为just
result = [character for character in string]
但是仍然有更短的解来做同样的事情。
列表构造函数可用于将任何可迭代对象(迭代器、列表、元组、字符串等)转换为列表。
>>> list('abc')
['a', 'b', 'c']
最大的优点是它在Python 2和Python 3中工作方式相同。
此外,从Python 3.5开始(多亏了强大的PEP 448),现在可以通过将任何可迭代对象解包为空列表文本来构建列表:
>>> [*'abc']
['a', 'b', 'c']
这比直接调用列表构造函数更简洁,在某些情况下也更有效。
我建议不要使用基于map的方法,因为map在Python 3中不会返回一个列表。请参阅如何在Python 3中使用筛选、映射和还原。
如果你想一次处理一个字符串字符。你有多种选择。
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
from itertools import chain
string = 'your string'
chain(string)
类似于list(string),但返回的生成器在使用点被延迟计算,因此内存效率高。
Split()内置函数只会在特定条件的基础上分离值,但在单个词中,它不能满足条件。因此,可以借助list()来解决。它在内部调用数组,并根据数组存储值。
假设,
a = "bottle"
a.split() // will only return the word but not split the every single char.
a = "bottle"
list(a) // will separate ['b','o','t','t','l','e']
如果你只需要一个字符数组:
arr = list(str)
如果你想用一个特定的分隔符分隔str:
# str = "temp//temps" will will be ['temp', 'temps']
arr = str.split("//")
您也可以在列表操作中使用extend方法。
>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
要分割字符串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)将使你的列表恢复到以前的字符串形式…
下面是一个很好的脚本,可以帮助你找到最有效的方法:
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")