Reputation: 424
Here is my list
a = [ 1, 2, 3, 6, 7, 9, 11, 14, 15, 16]
I want to return a new list like this
new_a = [ [1,2,3],
[6,7],
[9],
[11],
[14,15,16]
]
I'm pretty lost on how to actually achieve this.
Here's what I have tried. Don't laugh please
#!/usr/env python
a = [1,2,3,5,7,9,10,11,18,12,20,21]
a.sort()
final=[]
first = a.pop(0)
temp=[]
for i in a:
if i - first == 1:
temp.append(first)
temp.append(i)
first=i
else:
final.append(set(temp))
first=i
temp=[]
print final
[set([1, 2, 3]), set([]), set([]), set([9, 10, 11, 12]), set([])]
Thanks stackoverflow a noob like me can learn :DDD #CoDeSwAgg
Upvotes: 2
Views: 59
Reputation: 309929
You can do this with a bit of clever itertools work:
[[v[1] for v in vals] for _, vals in itertools.groupby(enumerate(a), key=lambda x: x[1] - x[0])]
To break it down a bit more naturally:
result = []
groups = itertools.groupby(enumerate(a), key=lambda x: x[1] - x[0])
for _, values in groups:
result.append([v[1] for v in values])
Upvotes: 3
Reputation: 15433
out = []
for i in xrange(len(a)):
if i == 0:
sub = [a[0]]
elif a[i] == a[i-1]+1:
sub.append(a[i])
else:
out.append(sub)
sub = [a[i]]
out.append(sub)
print out
# [[1, 2, 3], [6, 7], [9], [11], [14, 15, 16]]
disclaimer: your list needs to be sorted first
Upvotes: 1
Reputation: 1849
a = [1, 2, 3, 6, 7, 9, 11, 14, 15, 16]
def group_by_adjacent(l):
groups = []
current_group = []
for item in l:
if len(current_group) == 0 or item - 1 == current_group[-1]:
current_group.append(item)
else:
groups.append(current_group)
current_group = [item]
return groups
print group_by_adjacent(a)
This will work if your list is sorted and does not contain duplicates.
If you need to sort the list, please take a look at how to sort in Python
Upvotes: 1