首页 > 解决方案 > 用空格分割列表列表中的字符串

问题描述

假设我有以下结构:

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)

但我想知道是否有更易读、可能更有效的算法来解决这个问题。

标签: pythonstringlist

解决方案


您可以制作一个简单的生成器来产生拆分,然后在列表理解中使用它:

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']]

推荐阅读