在python中拆分整个字符串列表

2024-10-02 10:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表中的python字符串列表。你知道吗

我想在列表中的每个字符串上调用split方法,并将结果存储在另一个列表中,而不使用循环,因为列表非常长。你知道吗

编辑1 这里有一个例子

   input = ["a,the,an","b,b,c","people,downvoting,it,must,think,first"]

   output  [["a","the","an"],["b","b","c"],["people","downvoting","it","must","think","first"]]

用于拆分的分隔符是“,”

有什么窍门吗?你知道吗


Tags: the方法字符串an编辑列表inputit
3条回答

如果您想要一个平面列表,而不是列表列表:

from itertools import chain
list_out = list(reduce(chain, [string.split() for string in lists_in]))

使用列表理解。你知道吗

mystrings = ["hello world", "this is", "a list", "of interesting", "strings"]
splitby = " "
mysplits = [x.split(splitby) for x in mystrings]

不知道它的性能是否比for循环好,但你可以这样做。你知道吗

[a.split(',') for a in list]

Sample: ['a,c,b','1,2,3']
Result: [['a','c','b'],['1','2','3']]

如果你想把所有的东西都列在一个列表里,你可以试试这个(不知道效率有多高)

output = sum([a.split(',') for a in list],[])
Sample: ['a,c,b','1,2,3']
Result: ['a','c','b','1','2','3']

相关问题 更多 >

    热门问题