python:列表的字典是以某种方式耦合的

2024-09-30 20:34:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个小python程序来迭代数据文件(input_file)并执行计算。如果计算结果达到某些状态(stateAstateB),则从结果中提取信息(点击)。要提取的命中取决于三个参数集中的参数。
我使用字典来存储我的参数集(param_sets)和列表字典来存储命中率(hits)。字典param_sets点击具有相同的键。在

问题是

hits字典中的列表是以某种方式耦合的。当一个列表更改时(通过调用extract_hits函数),其他列表也会更改。在

这里是(简称)代码:

import os, sys, csv, pdb
from operator import itemgetter

# define three parameter sets
param_sets = {
    'A' : {'MIN_LEN' : 8, 'MAX_X' : 0, 'MAX_Z' : 0},
    'B' : {'MIN_LEN' : 8, 'MAX_X' : 1, 'MAX_Z' : 5},
    'C' : {'MIN_LEN' : 9, 'MAX_X' : 1, 'MAX_Z' : 5}}

# to store hits corresponding to each parameter set
hits = dict.fromkeys(param_sets, [])

# calculations
result = []
for input_values in input_file:
    # do some calculations
    result = do_some_calculations(result, input_values)
    if result == stateA:
        for key in param_sets.keys():
            hits[key] = extract_hits(key, result,
                                                hits[key],
                                                param_sets[key]['MIN_LEN'],
                                                param_sets[key]['MAX_X'],
                                                param_sets[key]['MAX_Z'])
        result = []  # discard results, start empty result list
    elif result == stateB:
        for key in param_sets.keys():
            local_heli[key] = extract_hits(key,
                                           result,
                                           hits[key],
                                           param_sets[key]['MIN_LEN'],
                                           param_sets[key]['MAX_X'],
                                           param_sets[key]['MAX_Z'])
        result = [] # discard results
        result = some_calculation(input_values) # start new result list
    else:
        result = some_other_calculation(result) # append result list



def extract_hits(k, seq, hits, min_len, max_au, max_gu):
    max_len = len(seq)
    for sub_seq_size in reversed(range(min_len, max_len+1)):
        for start_pos in range(0,(max_len-sub_seq_size+1)):
            from_inc = start_pos
            to_exc = start_pos + sub_seq_size
            sub_seq = seq[from_inc:to_exc]
            # complete information about helical fragment sub_seq
            helical_fragment = get_helix_data(sub_seq, max_au, max_gu)
            if helical_fragment:
                hits.append(helical_fragment)
                # search seq regions left and right from sub_seq for further hits
                left_seq = seq[0:from_inc]
                right_seq = seq[to_exc:max_len]
                if len(left_seq) >= min_len:
                    hits = sub_check_helical(left_seq, hits, min_len, max_au, max_gu)
                if len(right_seq) >= min_len:
                    hits = sub_check_helical(right_seq, hits, min_len, max_au, max_gu)
                print 'key', k                 # just for testing purpose
                print 'new', hits              # just for testing purpose
                print 'frag', helical_fragment # just for testing purpose
                pdb.set_trace()                # just for testing purpose
                return hits # appended
    return hits # unchanged

这里是python调试器的一些输出:

^{pr2}$

来自键A的元素不应出现在键B中,键A和键B的元素不应出现在键C中。在


Tags: keyfromforinputlenparamsetsresult
2条回答

默认情况下,字典和列表是通过引用传递的。对于字典,而不是:

hits_old = hits      # just for testing purpose

它将是:

^{pr2}$

这将复制字典的键/值对,从而生成一个等效字典,该字典不包含将来对hits字典的更改。在

当然,第二个函数中的hits_old实际上是一个列表,而不是一个字典,因此您需要执行类似以下操作来复制它:

hits_old = hits[:]

我不知道为什么列表没有copy()函数,以防您疑惑。在

你的台词:

hits = dict.fromkeys(param_sets, [])

相当于:

^{pr2}$

也就是说,hits中的每个条目都有相同的list对象作为其值,最初是空的,不管它有什么键。请记住,赋值不执行隐式复制:相反,它指定“对RHS对象的另一个引用”。在

你想要的是:

hits = dict()
for k in param_sets:
    hits[k] = []

也就是说,一个新的单独的列表对象作为每个条目的值。相当于

hits = dict((k, []) for k in param_sets)

顺便说一句,当您需要创建容器的(浅)副本时,最常用的方法通常是调用容器的类型,以旧容器作为参数,如:

newdict = dict(olddict)
newlist = list(oldlist)
newset = set(oldset)

以此类推;这还可以在类型之间转换容器(newlist = list(oldset)从集合中生成一个列表,依此类推)。在

相关问题 更多 >