Last active
February 6, 2021 14:01
-
-
Save su79eu7k/b1e2e476b120371d8f2e9825229e0dc2 to your computer and use it in GitHub Desktop.
grouping/chunking elements with last_index.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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