简体   繁体   中英

How to convert a list of lists into a list of tuple + list

I have a list of lists, such as

l =  ["{{{1star}}} Do not bother with this  restaurant.",  "{{{1star}}}
The food is good but the service is awful."]

I would like to convert this list into a different list. The new list would contain a tuple and another list. The first element of the tuple would be what is inside {{}} as a string and the second element of the tuple would contain the rest of the text as a list. I am expecting the following output:

output =  [("{{{1star}}}", ["Do not bother with this  restaurant."]), 
("{{{1star}}}", ["The food is good but the service is awful."])]

Thank you!

i tried to get what you want with some string manipulation

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)

or using regex

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM