I'm new in Python but basically I want to create sub-groups of element from the list with a double loop, therefore I gonna compare the first element with the next to figure out if I can create these sublist, otherwise I will break the loop inside and I want continue with the last element but in the main loop:
Example: 5,7,8,4,11
Compare 5 with 7, is minor? yes so include in the newlist and with the inside for continue with the next 8, is minor than 5? yes, so include in newlist, but when compare with 4, I break the loop so I want continue in m with these 4 to start with the next, in this case with 11...
for m in xrange(len(path)):
for i in xrange(m+1,len(path)):
if (path[i] > path[m]):
newlist.append(path[i])
else:
break
m=m+i
Thanks for suggestions or other ideas to achieve it!
P.S.
Some input will be:
input: [45,78,120,47,58,50,32,34]
output: [45,78,120],[47,58],50,[32,34]
The idea why i want make a double loops due to to compare sub groups of the full list,in other way is while 45 is minor than the next one just add in the new list, if not take the next to compare in this case will be 47 and start to compare with 58.
I used a double loop as well, but put the inner loop in a function:
The prefix function basically splits a list into 2; the first part is composed of the first ascending numbers, the second is the rest that still needs to be processed (or the empty list, if we are done).
The main function then simply assembles the first parts in a result lists, and hands the rest back to the inner function.
I'm not sure about the single value 50; in your example it's not in a sublist, but in mine it is. If it is a requirement, then change
to
No loop! Well at least, no explicit looping...
Usage (work both with Python 2 & Python 3):
Joke apart, if you need to group items in a list
itertools.groupby
deserves a little bit of attention. Not always the easiest/best answer -- but worth to make a try...EDIT: If you don't like closures -- and prefer using an object to hold the state, here is an alternative:
EDIT2: Since I prefer closures ... but @torek don't like the dictionary syntax, here a third variation around the same solution:
@uselpa's version is fine. Here's mine (same issue with [50] instead of just 50) that uses
collections.deque
to be a little more efficient, and also some long comments...(Incidentally, in the days before
collections.deque
I'd probably just use a reversed copy oflst
and uselst.pop()
insublist
. That's not quite as obvious, though.)