首页 > 解决方案 > regex to separate items in a list

问题描述

I need to separate items from within a list, meaning I have a list of items, but some of the items are also lists. I need some way to separate the lists within the list while keeping all items from the original list.

The input is something like this:

['lexapro, losartan, lunesta, hormonal supplements', 'prozac 10mg', 'mesalamine, entiviyo, various vitamin supplements', 'none', 'none', '', 'spironolactone 100mg twice a day', 'zoloft', 'blood pressure medications', 'sleep, cholestral, migrain, phentermine']

and I want the output to be:

['lexapro', 'losartan', 'lunesta', 'hormonal supplements', 'prozac 10mg', 'mesalamine', 'entiviyo', 'various vitamin supplements', 'none', 'none', 'spironolactone 100mg twice a day', 'zoloft', 'blood pressure medications', 'sleep', 'cholestral', 'migrain', 'phentermine']

I have used this:

separate = re.findall(r'(\d+)(,\s*\d+)*', medicine_list)

with no luck. medicine_list is the original list. Any thoughts?

标签: pythonregex

解决方案


这可以使用循环和拆分功能轻松完成,

medicine_list = ['lexapro, losartan, lunesta, hormonal supplements', 'prozac 10mg', 'mesalamine, entiviyo, various vitamin supplements', 'none', 'none', '', 'spironolactone 100mg twice a day', 'zoloft', 'blood pressure medications', 'sleep, cholestral, migrain, phentermine']

list_of_lists = [w.split(",") for w in medicine_list] # convert to list of lists
print([item for sublist in list_of_lists for item in sublist]) 
#traverse sublists and pick items in them one by one and put them 
#in one final list using list comprehension

推荐阅读