在python中拆分列表的项目

pyd*_*pyd 2 python listview list

嗨,我有一个清单,

 my_list=["one two","three four"] 
Run Code Online (Sandbox Code Playgroud)

我想要的输出是,

output_list=['one', 'two', 'three', 'four']
Run Code Online (Sandbox Code Playgroud)

我试过下面的代码,

 my_list=" ".join(my_list)
 output_list=my_list.split()
 output_list,
 ['one', 'two', 'three', 'four']
Run Code Online (Sandbox Code Playgroud)

它工作正常,我得到我的输出,我希望,解决方案比这更短的解决方案可以实现相同,在此先感谢!

cs9*_*s95 5

一个简单的嵌套列表理解应该做得很好:

>>> [y for x in my_list for y in x.split()] 
['one', 'two', 'three', 'four']
Run Code Online (Sandbox Code Playgroud)

或者,使用itertools.chain:

>>> from itertools import chain 
>>> list(chain.from_iterable(map(str.split, my_list)))
['one', 'two', 'three', 'four']
Run Code Online (Sandbox Code Playgroud)

有趣的是,str.join和随之而来的str.split是你的建议是最短的版本!

>>> " ".join(my_list).split()
['one', 'two', 'three', 'four']
Run Code Online (Sandbox Code Playgroud)

ᴘᴇʀғᴏʀᴍᴀɴᴄᴇ

my_list = ['foo bar' for _ in range(1000000)]
Run Code Online (Sandbox Code Playgroud)
%timeit  [y for x in my_list for y in x.split()]
1 loop, best of 3: 554 ms per loop
Run Code Online (Sandbox Code Playgroud)
%timeit list(chain.from_iterable(map(str.split, my_list)))
1 loop, best of 3: 519 ms per loop  # yes, this surprised me too.
Run Code Online (Sandbox Code Playgroud)
%timeit " ".join(my_list).split()
1 loop, best of 3: 200 ms per loop
Run Code Online (Sandbox Code Playgroud)