[英]Pythonic way to walk a self-referential dictionary
我有一個字典,其中條目值可以通過鍵引用另一個條目,最終沒有當前值的條目或遇到“ - ”時。 此數據結構的目標是找到每個條目的父級,並將“ - ”轉換為None。 例如:
d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
我的詳細解決方案如下:
d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
print(d)
for dis, rep in d.items():
if rep == "-":
d[dis] = None
continue
while rep in d:
rep = d[rep]
if rep == "-":
d[dis] = None
break
else:
d[dis] = rep
print(d)
輸出是:
{'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
{'1': None, '0': '9', '3': None, '2': None, '4': '5', '6': '9'}
結果是正確的。 “1”元素沒有父元素,“2”/“3”元素指向“1”。 他們也應該沒有父母。
使用Python 3+有沒有更簡潔的pythonic方法來實現這一目標?
要“遍歷”字典,只需在循環中執行查找,直到不再有:
>>> def walk(d, val):
while val in d:
val = d[val]
return None if val == '-' else val
>>> d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
>>> print {k: walk(d, k) for k in d}
{'1': None, '0': '9', '3': None, '2': None, '4': '5', '6': '9'}
您可以定義這樣的函數
def recursive_get(d, k):
v = d[k]
if v == '-':
v = d[k] = None
elif v in d:
v = d[k] = recursive_get(d, v)
return v
當您使用recursive_get
訪問密鑰時,它將在遍歷時修改值。 這意味着您不會浪費時間來收拾從不需要的分支
>>> d = {'1': '-', '3': '1', '2': '3'}
>>> recursive_get(d, '3')
>>> d
{'1': None, '3': None, '2': '3'} # didn't need to visit '2'
>>> d = {'1': '-', '3': '1', '2': '3'}
>>> recursive_get(d, '2')
>>> d
{'1': None, '3': None, '2': None}
如果你想強迫d
進入它的最終狀態,只需循環遍歷所有鍵
for k in d:
recursive_get(d, k)
我想發布一些關於這三種方法的分析統計數據:
Running original procedural solution.
5 function calls in 0.221 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.221 0.221 <string>:1(<module>)
1 0.221 0.221 0.221 0.221 test.py:12(verbose)
1 0.000 0.000 0.221 0.221 {built-in method exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}
885213
Running recursive solution.
994022 function calls in 1.252 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.252 1.252 <string>:1(<module>)
994018 0.632 0.000 0.632 0.000 test.py:27(recursive)
1 0.620 0.620 1.252 1.252 test.py:35(do_recursive)
1 0.000 0.000 1.252 1.252 {built-in method exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
885213
Running dict comprehension solution.
994023 function calls in 1.665 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.059 0.059 1.665 1.665 <string>:1(<module>)
994018 0.683 0.000 0.683 0.000 test.py:40(walk)
1 0.000 0.000 1.606 1.606 test.py:45(dict_comprehension)
1 0.923 0.923 1.606 1.606 test.py:46(<dictcomp>)
1 0.000 0.000 1.665 1.665 {built-in method exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
885213
下面是運行這三種方法的代碼:
import cProfile
import csv
import gzip
def gzip_to_text(gzip_file, encoding="ascii"):
with gzip.open(gzip_file) as gzf:
for line in gzf:
yield str(line, encoding)
def verbose(d):
for dis, rep in d.items():
if rep == "-":
d[dis] = None
continue
while rep in d:
rep = d[rep]
if rep == "-":
d[dis] = None
break
else:
d[dis] = rep
return d
def recursive(d, k):
v = d[k]
if v == '-':
v = d[k] = None
elif v in d:
v = d[k] = recursive(d, v)
return v
def do_recursive(d):
for k in d:
recursive(d, k)
return d
def walk(d, val):
while val in d:
val = d[val]
return None if val == '-' else val
def dict_comprehension(d):
return {k : walk(d, k) for k in d}
# public dataset pulled from url: ftp://ftp.ncbi.nih.gov/gene/DATA/gene_history.gz
csvr = csv.reader(gzip_to_text("gene_history.gz"), delimiter="\t", quotechar="\"")
d = {rec[2].strip() : rec[1].strip() for rec in csvr if csvr.line_num > 1}
print("Running original procedural solution.")
cProfile.run('d = verbose(d)')
c = 0
for k, v in d.items():
c += (1 if v is None else 0)
print(c)
print("Running recursive solution.")
cProfile.run('d = do_recursive(d)')
c = 0
for k, v in d.items():
c += (1 if v is None else 0)
print(c)
print("Running dict comprehension solution.")
cProfile.run('d = dict_comprehension(d)')
c = 0
for k, v in d.items():
c += (1 if v is None else 0)
print(c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.