用数字替换Python列表中的哈希值。

4

我有以下列表:

l = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']

如果存在一个哈希,我想用1.代替它;如果序列中有两个哈希,我想为第一个双重哈希获取1.1,为第二个哈希获取1.2.。下一个单一哈希我想得到2.,以此类推,遵循这个逻辑。
结果应该是这样的:
1. Cars
1.1 duo
1.2 go
2. hello 
2.2 there
3个回答

7

尝试这个:

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']

如果您不想保留没有哈希值的项目,只想进行打印输出,那么请使用以下内容:

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

更通用的方法:

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

1
一种更短的递归解决方案:
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)))

输出:

1 Cars
1.1 duo
1.2 go
2 hello
2.1 there

1
你可以追踪顶级号码和子级号码,也可以像这样:-
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)

这里发生的事情是,循环遍历每个字符串,并检查该字符串是否以"##"开头。如果以此开头,它将增加子级编号并用格式top.nxt替换"##",如果该字符串以单个井号"#"开头,则增加顶部编号,将子级编号设置为0,并用顶部编号替换"#"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接