简体   繁体   中英

How to split a list of a giant single string into seperate substrings

So I have a list of 3 giant strings, such as:

lst=['Mary,had,"3",little-lambs','Mary,sold-her,"3",lambs,away','Mary,was,sad']

that list has giant strings, but I want to split those strings into seperate little strings in a list (so for the first one I want:

ls=['Mary','had','3','little','lambs'] 

and so on. I tried

.split

but it wont work because its a list and that is a string method. I need a completely non-pythonic way please. (Also if anyone can help with the next step, I'm tring to put the last value (in this case lambs,away,sad into a dictionary as keys to mary. For example like:

dictionary={"lambs": "Mary","away":"Mary","sad":"Mary"}

because later I need to indicate to Mary(the values), and all the keys associated with Mary should pop up. If anyone can help it would be greatly appreciated, I'm really stuck, and any help should be completely non-pythonic please.

Edit: I have used a for loop and split each thing and appended it to a new list, but the result creates a list of the list of strings

lst1=[]
for item in lst:
    item=item.split(",")
    lst1.append(item)
print(content)
print(lst1)

lst1=[['Mary','had','3','little','lambs']]

I'm trying to avoid creating a list inside another list because I dont know how to index each part of it to create the dictionary I mentioned earlier

EDIT: Changed the split to be a re.split including regex specifically for the "," and "-" characters. Should be modified to match necessary delimiters. This will give you the dictionary you need. You can append tokens to a separate list to get a list of the individual words per string.

import re
last_keys = dict()
for item in lst:
    tokens = re.split(r',|\-', item)
    last_keys[tokens[-1]] = "Mary"

Just use re.split() in the above answer.

import re
last_keys = dict()
for item in lst:
     tokens = re.split('-|,',item)
     last_keys[tokens[-1]] = "Mary"

last_keys
{'lambs': 'Mary', 'away': 'Mary', 'sad': 'Mary'}

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