首页 > 解决方案 > 如何将列表列表转换为元组列表+列表

问题描述

我有一个列表列表,例如

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."])]

谢谢!

标签: pythonlisttuples

解决方案


我试图通过一些字符串操作来得到你想要的

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)

推荐阅读