首页 > 解决方案 > Split and Append a list

问题描述

I have a list as follows:

['aaa > bbb', 'ccc > ddd', 'eee >  ']

I am looking to split the list to get the following result, with an empty string element at the end

['aaa', 'bbb', 'ccc', 'ddd', 'eee',''] 

I tried the following code

for element in list:
    list.append(element.split(' > '))

I am getting answer as follows:

[['aaa', 'bbb'], ['ccc', 'ddd'], ['eee','']] 

After thinking I see that is what it supposed to work as. So how can I achieve what I am looking for.

标签: pythonlist

解决方案


您可以使用列表理解:

l = ['aaa > bbb', 'ccc > ddd', 'eee >  ']
[item.strip() for sublist in [element.split(">") for element in l] for item in sublist]

输出是:

['aaa', 'bbb', 'ccc', 'ddd', 'eee', '']

我承认这个列表理解不是超级容易理解,但它是单行的:)


推荐阅读