繁体   English   中英

如何在单独的列表中拆分字符串中的每个单词

[英]how to split each word in a string in a seperate list

我如何在单独的字符串中拆分字符串中的每个单词? 例如,如果我有这个代码

s = "It sure is a nice day today"
l = list(s)

这将返回['I', 't', ' ', 's', 'u', 'r', 'e', ' ', 'i', 's', ' ', 'a', ' ', 'n', 'i', 'c', 'e', ' ', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y']相反,我想让它像这样返回单独的列表:

['I', 't']
['s', 'u', 'r', 'e']
['i', 's']
['a']
['n', 'i', 'c', 'e']
['d', 'a', 'y']
['t', 'o', 'd', 'a', 'y']

如果可能的话,将它们存储在单独的列表中,而不是简单地打印它们。

这看起来像列表 ,因为您需要一些数据结构来存储这些子列表。

例如:

s = "It sure is a nice day today"
result = [list(si) for si in s.split()]

然后生成:

>>> result = [list(si) for si in s.split()]
>>> result
[['I', 't'], ['s', 'u', 'r', 'e'], ['i', 's'], ['a'], ['n', 'i', 'c', 'e'], ['d', 'a', 'y'], ['t', 'o', 'd', 'a', 'y']]

当然,您也可以将这些子列表存储在元组等中。但不知何故,您必须将这些子列表包装到可以存储列表的集合中。

基于map的无可挑剔的版本@WillemVanOnsem的答案:

list(map(list, s.split()))
#[['I', 't'], ['s', 'u', 'r', 'e'], ['i', 's'], ['a'], ['n', 'i', 'c', 'e'], ['d', 'a', 'y'], ['t', 'o', 'd', 'a', 'y']]

如果你想分割一个字符串,这就是我通常的做法

   var S= "my name is sam",
   K= s.split (''),
   FirstLetter= k [0];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM