Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substitute hash with numbers in list python

Tags:

python

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
like image 258
moth Avatar asked Dec 31 '22 12:12

moth


1 Answers

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 more general method:

def hash(a):
    v = []
    for s in a:
        
        i = 0
        while s[i] == "#":
            i += 1
        
        if i > 0:
            if len(v) < i:
                v += [0] * (i - len(v))
            else:
                for j in range(i, len(v)):
                    v[j] = 0
            
            v[i - 1] += 1
            
            s = "%s %s" % (".".join(str(j) for j in v[:i]), s[i:])
            print(s)

a = ["#a", "##b", "###c", "###d",  "#e", "##f", "###g", "##h", "###i", "####j", "#k"]
hash(a)
1 a
1.1 b
1.1.1 c
1.1.2 d
2 e
2.1 f
2.1.1 g
2.2 h
2.2.1 i
2.2.1.1 j
3 k
like image 172
Jean-Claude Arbaut Avatar answered Jan 04 '23 15:01

Jean-Claude Arbaut