Issue
Given a string like /root/2/1/2
, how do we construct the following list:
['/root/2/1/2', 'root/2/1', 'root/2', '/root']
Solution
A very simple implementation is to split once from the right side on /
character iteratively until there is nothing left.
left = '/root/2/1/2'
lst = []
while left:
lst.append(left)
left, right = left.rsplit('/', 1)
print(lst) # ['/root/2/1/2', '/root/2/1', '/root/2', '/root']
Using the walrus operator, we can also write it in a single line (much less readable than the while loop though):
left = '/root/2/1/2'
lst = [left, *(left for _ in range(left.count('/')) if (left:=left.rsplit('/', 1)[0]))]
Answered By - cottontail
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.