python - 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?
解决方案
这可以使用循环和拆分功能轻松完成,
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
推荐阅读
- javascript - 如何为不同的 Vue 布局使用不同的资源?
- laravel - 在 Kubernetes pod 中,不能强制 Laravel Echo(使用 Pusher)通过端口 6001 协议而不是端口 443 上的 wss 连接
- php - 数组未将正确形式的控制器渲染到树枝
- r - 安排多个 R 脚本按顺序运行
- c# - 如何继续添加带有免费响应文本框的整数?
- python - 如何将新列添加到具有 0 和 1 值的特定列的值的数据框中
- excel - 更改活动工作表上的数据时,下工作表上的 VBA Excel 自动增量值
- java - 最大化 JFrame | 没有全屏
- google-cloud-platform - 在 GKE 气流中通过 KubernetesPodOperator 安装卷问题
- react-native - 如何在本机反应中将整个屏幕分成各种大小的部分