Pythonic的方式走自我指涉词典

时间:2012-04-19 01:46:35

标签: dictionary python-3.x python

我有一个字典,其中条目值可以通过键引用另一个条目,最终没有当前值的条目或遇到“ - ”时。此数据结构的目标是找到每个条目的父级,并将“ - ”转换为None。例如:

d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
  • '1'是映射到' - '的根,因此它应该导致
  • '0'的父级为'6',其父级为'9',因此它应该为'9'。
  • '3'的父级为'1',映射为' - ',因此它应该导致
  • '2'的父级为'3',其父级为'1',映射为' - ',因此它应该导致
  • '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方法来实现这一目标?

3 个答案:

答案 0 :(得分:4)

要“走”字典,只需在循环中进行查找,直到不再有:

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

答案 1 :(得分:1)

您可以定义类似这样的功能

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)

答案 2 :(得分:1)

我想发布一些关于这三种方法的分析统计数据:

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)