Converting One List Into Individual Ones
Solution 1:
You could use itertools groupby:
import itertools
l = ['t' , 'r', 'q', ']', '[' , 'd', 'e', 'n', ']' , '[', 'l', 't']
new_l = [list(group) for i, group in itertools.groupby(l,
lambda x: x in [']', '[']) if not i]
# [['t', 'r', 'q'], ['d', 'e', 'n'], ['l', 't']]
You could do it also without lambda (credit goes to Jon Clements):
new_l = [list(group) for i, group in itertools.groupby(l,
set('[]').intersection) if not i]
Solution 2:
Since you don't seem to have leading & trailing brackets, I would join them into a string then split them:
joinedList = "".join(list)
splitList = joinedList.split('][')
From your code (and as pointed out in the comments), list
looks a bit strange and might have been a complete string before. You might want to process variables that gave you list
instead.
Solution 3:
An alternative approach:
temp=[]
final=[]
for item in list:
if item != ']':
temp.append(item)
else:
final.append(temp)
temp=[]
I guess the only advantage here is that items don't have to be strings.
But as it has been pointed out in the comments, you should probably avoid having this kind of a list in the first place...
Solution 4:
Agree with the other posters that it seems like you've ended up with weird looking input.
If your input is really for sure formatted like you say, and you're sure that you won't have malformed input, you can do what you want like so:
input = ['t' , 'r', 'q', ']', '[' , 'd', 'e', 'n', ']' , '[', 'l', 't']
scratch = list(input)
output = []
def find_bracket(L):
try:
return L.index(']')
except:
return -1
bracket_index = find_bracket(scratch)
while bracket_index > 0:
output.append( scratch[:bracket_index] )
scratch = scratch[bracket_index+2:]
bracket_index = find_bracket(scratch)
output.append( scratch )
print output
Gives me:
[['t', 'r', 'q'], ['d', 'e', 'n'], ['l', 't']]
Solution 5:
Try this -
>>> li = ['t' , 'r', 'q', ']', '[' , 'd', 'e', 'n', ']' , '[', 'l', 't']
>>> list1, list2, list3 = [[c for c in a] for a in "".join(li).split("][")]
#OUTPUT
>>> list1
['t', 'r', 'q']
>>> list2
['d', 'e', 'n']
>>> list3
['l', 't']
Post a Comment for "Converting One List Into Individual Ones"