python - 如何将列表列表转换为元组列表+列表
问题描述
我有一个列表列表,例如
l = ["{{{1star}}} Do not bother with this restaurant.", "{{{1star}}}
The food is good but the service is awful."]
我想将此列表转换为不同的列表。新列表将包含一个元组和另一个列表。元组的第一个元素将是内部{{}}
的字符串,元组的第二个元素将包含文本的其余部分作为列表。我期待以下输出:
output = [("{{{1star}}}", ["Do not bother with this restaurant."]),
("{{{1star}}}", ["The food is good but the service is awful."])]
谢谢!
解决方案
我试图通过一些字符串操作来得到你想要的
l = ["{{{1star}}} Do not bother with this restaurant.", "{{{1star}}} The food is good but the service is awful."]
out = []
for strings in l :
s = strings.split()
first = s[0]
second = strings.replace(s[0],'')
tuple = ( first , second )
out.append(tuple)
print(out)
或使用正则表达式
import re
l = ["{{{1star}}} Do not bother with this restaurant.", "{{{1star}}} The food is good but the service is awful."]
out = []
for strings in l :
s = re.match( r'(.*)\}(.*?) .*', strings, re.M|re.I)
print(s)
if s :
first = s.group(1) + '}'
second = strings.replace(first,'')
tuple = ( first , second )
out.append(tuple)
print(out)
推荐阅读
- javascript - Vue在单击时发出另一个元素的引用
- curl - 我需要 curl 查询来检查我的 Splunk 的连接性
- angularjs - 我们如何在 AngularJS 中解析 JSON 数据
- ios - Facebook 原生广告未在 iOS 中加载?
- c - Source Insight 无法识别多行宏
- python-2.7 - python中更快的“switch-case”实现
- php - 封闭日期间隔的正则表达式
- oracle - 将 Oracle Apex 应用程序发布并托管到 WWW 中
- wordpress - 如何在 woocommerce 产品描述页面中添加默认文本
- ios - 如何在后台快速跟踪用户位置