Skip to content

Instantly share code, notes, and snippets.

@su79eu7k
Last active February 6, 2021 14:01
Show Gist options
  • Save su79eu7k/b1e2e476b120371d8f2e9825229e0dc2 to your computer and use it in GitHub Desktop.
Save su79eu7k/b1e2e476b120371d8f2e9825229e0dc2 to your computer and use it in GitHub Desktop.
grouping/chunking elements with last_index.
def handle_last_index(elements, last_index):
grouped = []
for i, _ in enumerate(last_index):
if i == 0:
grouped.append(' '.join(elements[:last_index[i] + 1]))
elif i == len(last_index) - 1:
grouped.append(' '.join(elements[last_index[i - 1] + 1:]))
else:
grouped.append(' '.join(elements[last_index[i - 1] + 1:last_index[i] + 1]))
return grouped
print(handle_last_index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], [2, 5, 7]))
# ['a b c', 'd e f', 'g h']
print(handle_last_index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], [0, 3, 8]))
# ['a', 'b c d', 'e f g h']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment