python - 用空格分割列表列表中的字符串
问题描述
假设我有以下结构:
t = [['I will','take','care'],['I know','what','to','do']]
正如您在我拥有的第一个列表中看到的'I will'
,我希望它们分成两个元素'I'
,并且'will'
st 结果是:
[['I', 'will', 'take', 'care'], ['I', 'know', 'what', 'to', 'do']]
快速而肮脏的算法如下:
train_text_new = []
for sent in t:
new = []
for word in sent:
temp = word.split(' ')
for item2 in temp:
new.append(item2)
train_text_new.append(new)
但我想知道是否有更易读、可能更有效的算法来解决这个问题。
解决方案
您可以制作一个简单的生成器来产生拆分,然后在列表理解中使用它:
t = [['I will','take','care'],['I know','what','to','do']]
def splitWords(l):
for words in l:
yield from words.split()
[list(splitWords(sublist)) for sublist in t]
# [['I', 'will', 'take', 'care'], ['I', 'know', 'what', 'you', 'to', 'do']]
推荐阅读
- python - 为什么我会收到此错误?'_io.TextIOWrapper' 对象没有属性 'append'
- c++ - 如果为 false,std::is_member_function_pointer 不会编译
- c# - Microsoft.AspNetCore.App - 版本控制/是否应该在非 ASP.NET 类库中引用?
- php - phpcs 一直扫描整个项目而不是指定目录
- jquery - Laravel5.8 jQuery发布请求说它是一个获取路线
- konvajs - Konva JS - 带有图像的工具提示
- angular - 如果 TS 文件中的导入不是相关路径,则为移动中断构建 Nativescript
- c# - 在 Web API 中设置 ZipArchive Zip 文件的名称
- excel - 如何在 MS Excel 中制作动画形状
- jupyter-notebook - 在 jupyter 笔记本中隐藏带密码的单元格