3

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

d = {'1': '-', '0': '6', '3': '1', '2': '3', '4': '5', '6': '9'}
  • '1' 是映射到 '-' 的根,因此它应该导致None
  • '0' 的父级是 '6',它的父级是 '9',所以它应该是 '9'。
  • '3' 有一个 '1' 的父级,它映射到 '-' 所以它应该导致None
  • '2' 有一个 '3' 的父级,它有一个 '1' 的父级映射到 '-' 所以它应该导致None
  • '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+ 的更简洁的 Python 方式来完成此任务?

4

3 回答 3

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'}
于 2012-04-19T02:55:26.753 回答
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)
于 2012-04-19T17:56:43.927 回答
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)
于 2012-04-19T02:28:31.843 回答