[英]substitute hash with numbers in list 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.
我想替换为
1.
的第一个散列1.
如果有两个散列,我想为序列中的第一个双散列获得1.1
和1.2.
for the second hash.对于第二个哈希。 The next single hash I would like to have
2.
and so on so forth with this logic.下一个散列我想要
2.
依此类推这个逻辑。
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.这里发生的事情是,循环获取每个字符串并检查字符串是否以
"##"
开头,如果以"##"
开头,则增加子级别编号并用格式top.nxt
替换"##"
,如果string 以单个散列"#"
开头,然后递增顶部编号,将子级别编号设置为 0 并将"#"
替换为顶部编号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.