将单个索引列表拆分为多个列表索引?

时间:2019-02-06 01:59:31

标签: python list

我有一个列表:

lst = ['words in a list']

,我希望将字符串中的每个单词拆分成各自独立的索引。因此,例如,它看起来像这样:

lst = ['words','in','a','list']

我想知道这是否可能吗?我最初以为这只是一个带循环的简单lst.split(),但看来这会引发错误。

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

使用此:

print(lst[0].split())

如果列表包含更多元素:

print([x for i in lst for x in i.split()])

答案 1 :(得分:1)

Split仅适用于字符串类型。因此,您需要先为列表项建立索引,然后再拆分。

lst = lst [0] .split()

答案 2 :(得分:0)

当列表中有一个字符串列表或单个字符串时,请使用

 lst = ['this is string1', 'this is string2', 'this is string3']
 result =' '.join(lst).split()
 print(result)
 # output : ['this', 'is', 'string1', 'this', 'is', 'string2', 'this', 'is', 'string3']
相关问题