python - 在Python中的字符串列表中提取特定字符串
问题描述
我有一个字符串列表:
List = ["A: I want to do something cool!|B: Really? What is that?|A: Lets me show you.", "A: How do you think about it?!|B: It's not bad|A: Thank you. What do you up to?|B: I have no idea. Lets hangaround|B: or maybe we can go for a drink."]
我想将信息提取到 2 个单独的列表中,每个列表都包含 A 和 B 的内容。
例如:
List_A = ['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']
List_B = ['B: Really? What is that?', 'B: It's not bad', 'I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']
有没有办法在 Python 中执行任务?我真的很感激帮助!
解决方案
尝试使用列表推导:
List = sum([i.split('|') for i in List], [])
List_A = [i for i in List if i[0] == "A"]
List_B = [i for i in List if i[0] == "B"]
现在:
print(List_A)
将会:
['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']
和:
print(List_B)
将会:
['B: Really? What is that?', "B: It's not bad", 'B: I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']
推荐阅读
- testing - RICO-Dataset - .json 文件基于哪种格式?
- java - 在受密码保护的 ZipInputStream 目录中解压缩文件
- python - 谷歌云计算实例启动时如何自动运行python脚本
- php - Wocomerce 不允许我为我的产品使用外部图片
- quill - 未捕获的 ReferenceError:未定义 Quill
- node.js - 如何在mongodb中查询具有多个引用数组的文档?
- django - 我正在使用 pinax-referral 但是当我跟进时,我得到了 raise.self.model.DoesNotExist 以及无法配置记录器的值错误
- python-3.x - 比较字典和数据框中的值
- tensorflow - 如何使用 TensorFlow C API 从字符串张量中提取字符串?
- html - Typed.js 不适用于多个实例