'Return elements between specific indexes
Imagine a situation where you have a list of elements for example:
arr = ["h4", "p", "p", "h4", "p", "p", "p"] and list of indexes where h4 value
is:
idx = [0, 3].
My goal is to print out values between these indexes, so the output will be:
[["p", "p"], ["p", "p", "p"]].
In another words I want to print arr[0:3] and arr[3:] but I want to make it dynamic so for example with another array like
arr2 = ["h4", "p", "p", "h4", "p", "p", "p", "h4", "p"],
idx2 = [0, 3, 7]
the output will be:
[["p", "p"], ["p", "p", "p"], ["p"]] (i.e. arr2[0:3], arr[3:7], arr[7:]).
In every case h4 value will always be at the index 0.
I don't know if similar question was asked because I couldn't find and also I don't know if it is possible to do it. Maybe similar task is on leetcode, if someone knows something let me know.
Solution 1:[1]
By using the groupby function from the itertools package you can group the term of the list by a custom criteria, lambda term: term == 'p'. See docs for details.
import itertools as it
a = ["h4", "p", "p", "h4", "p", "p", "p", "h4", "p"]
grouped = [list(grp) for match, grp in it.groupby(a, lambda term: term == 'p') if match]
print(grouped)
Output
[['p', 'p'], ['p', 'p', 'p'], ['p']]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cards |
