python:根据条件拆分字符串列表

ujv3wf0j  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(367)

我的清单如下:

my_list =['[] [How, you, today] [] []','[] [the] [weather, nice, though] [] []']

我希望以某种方式拆分列表以获得以下输出。

output_list = ['[]', '[How, you, today]', '[]', '[]','[]', '[the]',
      '[weather, nice, though]', '[]', '[]']

我尝试了以下方法,但没有得到我想要的结果。

[word for line in my_list for word in line.split('')]
3qpi33ja

3qpi33ja1#

几乎。首先,以下内容产生您想要的内容-

[('[' + word) if i else word for line in my_list for i, word in enumerate(line.split(' ['))]

更具体地说,您似乎希望按空格字符拆分,但前提是它是新单词列表的开始。因此与 ' [' .
接下来,除了第一个列表外,每个列表都将缺少开头括号。因此,通过“手动”为除第一个之外的所有对象添加它(通过使用枚举索引),可以获得请求的输出。

lstz6jyr

lstz6jyr2#

此链接适用于java,但正则表达式是相同的:除括号中的空格外,按所有空格拆分字符串
在python中按正则表达式拆分(将导入re添加到脚本中):

rx = '\\s+(?![^\\[]*\\])'

# join strings into one string, then split back to list from there

output_list = re.split(rx, ' '.join(my_list))

# ['[]', '[How, you, today]', '[]', '[]', '[]', '[the]', '[weather, nice, though]', '[]', '[]']

相关问题