[英]How to substitute string in a text file with a couple of numbers in a list using python?
[英]substitute hash with numbers in list python
我有以下清單:
l = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']
我想替換為1.
的第一個散列1.
如果有兩個散列,我想為序列中的第一個雙散列獲得1.1
和1.2.
對於第二個哈希。 下一個散列我想要2.
依此類推這個邏輯。
結果應該是這樣的:
1. Cars
1.1 duo
1.2 go
2. hello
2.2 there
嘗試這個:
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
更短的遞歸解決方案:
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
您可以跟蹤頂級編號和子級別編號,也可以像這樣:-
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
替換"##"
,如果string 以單個散列"#"
開頭,然后遞增頂部編號,將子級別編號設置為 0 並將"#"
替換為頂部編號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.