优雅通用在Python中排序成字典?

时间:2013-11-26 04:11:33

标签: python dictionary numpy

列表理解是一个很好的结构,用于推广使用列表,以便可以优雅地管理列表的创建。是否有类似的工具来管理Python中的词典?

我有以下功能:

    # takes in 3 lists of lists and a column specification by which to group
def custom_groupby(atts, zmat, zmat2, col):
    result = dict()
    for i in range(0, len(atts)):
        val = atts[i][col]
        row = (atts[i], zmat[i], zmat2[i])
        try:
            result[val].append(row)
        except KeyError:
            result[val] = list()
            result[val].append(row)
    return result

    # organises samples into dictionaries using the groupby
def organise_samples(attributes, z_matrix, original_z_matrix):
    strucdict = custom_groupby(attributes, z_matrix, original_z_matrix, 'SecStruc')

    strucfrontdict = dict()
    for k, v in strucdict.iteritems():
        strucfrontdict[k] = custom_groupby([x[0] for x in strucdict[k]],                                            
                                [x[1] for x in strucdict[k]], [x[2] for x in strucdict[k]], 'Front')

    samples = dict()
    for k in strucfrontdict:
        samples[k] = dict()
        for k2 in strucfrontdict[k]:
            samples[k][k2] = dict()
            samples[k][k2] = custom_groupby([x[0] for x in strucfrontdict[k][k2]],
                    [x[1] for x in strucfrontdict[k][k2]], [x[2] for x in strucfrontdict[k][k2]], 'Back')
    return samples

这似乎很笨重。有优雅的方法可以用Python做几乎所有事情,我倾向于认为我错误地使用了Python。

更重要的是,我希望能够更好地概括这个函数,以便我可以指定字典中应该有多少“层”(不使用几个lambdas并以Lisp样式处理问题)。我想要一个功能:

# organises samples into a dictionary by specified columns
# number of layers could also be assumed by number of criterion
def organise_samples(number_layers, list_of_strings_for_column_ids)

这可以用Python做吗?

谢谢!即使没有办法在Python中优雅地完成它,任何有关使上述代码更优雅的建议都将非常受欢迎。

:: EDIT ::

对于上下文,属性对象,z_matrix和original_zmatrix都是Numpy数组的列表。

属性可能如下所示:

Type,Num,Phi,Psi,SecStruc,Front,Back
11,181,-123.815,65.4652,2,3,19
11,203,148.581,-89.9584,1,4,1
11,181,-123.815,65.4652,2,3,19
11,203,148.581,-89.9584,1,4,1
11,137,-20.2349,-129.396,2,0,1
11,163,-34.75,-59.1221,0,1,9

Z-matrices可能看起来像这样:

CA-1, CA-2, CA-CB-1, CA-CB-2, N-CA-CB-SG-1, N-CA-CB-SG-2
-16.801, 28.993, -1.189, -0.515, 118.093, 74.4629
-24.918, 27.398, -0.706, 0.989, 112.854, -175.458
-1.01, 37.855, 0.462, 1.442, 108.323, -72.2786
61.369, 113.576, 0.355, -1.127, 111.217, -69.8672

样品是dict {num => dict {num => dict {num =>元组(attributes,z_matrix)}}},有一行z矩阵。

1 个答案:

答案 0 :(得分:1)

  

列表理解是一个很好的结构,用于推广使用列表,以便可以优雅地管理列表的创建。是否有类似的工具来管理Python中的词典?

您是否尝试使用词典理解?

请参阅此great question about dictionary comperhansions