I have the following list:
l = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']
The first hash I want to substitute to 1.
if there are two hashes I want to get 1.1
for the first double hash in the sequence and 1.2.
for the second hash. The next single hash I would like to have 2.
and so on so forth with this logic.
The result should be like that:
1. Cars
1.1 duo
1.2 go
2. hello
2.2 there
Try this:
a = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']
def hash(a):
res = []
major = 0
minor = 0
for s in a:
if "#" in s:
if "##" in s:
minor += 1
s = s.replace("##", "%d.%d " % (major, minor))
else:
major += 1
minor = 0
s = s.replace("#", "%d " % major)
res.append(s)
return res
hash(a)
['1 Cars', 'Cars came into global', '1.1 duo', '1.2 go', '2 hello', '2.1 there']
If you don't want to keep items without a hash, and only want to print, then this:
def hash(a):
major = 0
minor = 0
for s in a:
if "#" in s:
if "##" in s:
minor += 1
s = s.replace("##", "%d.%d " % (major, minor))
else:
major += 1
minor = 0
s = s.replace("#", "%d " % major)
print(s)
hash(a)
1 Cars
1.1 duo
1.2 go
2 hello
2.1 there
A shorter recursive solution:
from collections import defaultdict
l = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']
def to_hash(d, p = []):
r, c, l = defaultdict(list), 0, None
for a, *b in d:
if a != '#' and p:
yield f'{".".join(map(str, p))} {"".join([a, *b])}'
elif a == '#':
r[l:=((c:=c+1) if b[0] != '#' else c)].append(''.join(b))
yield from [j for a, b in r.items() for j in to_hash(b, p+[a])]
print('\n'.join(to_hash(l)))
Output:
1 Cars
1.1 duo
1.2 go
2 hello
2.1 there
You can keep a track on the top-level number and the sub-level number, like this also:-
lst = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']
top, nxt = 0, 0
for i in range(len(lst)):
s = lst[i]
if s[:2] == "##":
nxt += 1
lst[i] = s.replace("##", f"{top}.{nxt} ")
elif "#" in s[:2]:
top += 1
nxt = 0
lst[i] = s.replace("#", f"{top}. ")
for i in lst:
print(i)
What happens here is that, the loop takes each string and checks if the string starts with "##"
if it starts with that it increases the sub-level number and replaces the "##"
with the format top.nxt
, if the string starts with a single hash, "#"
, then it increments the top number, sets the sub-level number to 0 and replaces the "#"
with the top number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.