列表理解是一个很好的结构,它可以概括使用列表,从而可以优雅地管理列表的创建。在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是错误的。你知道吗
更重要的是,我希望能够更好地概括这个函数,这样我就可以指定字典中应该有多少“层”(而不需要使用几个lambda和用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中没有一种优雅的方法,任何使上述代码更优雅的建议都将非常感激。你知道吗
*编辑::
对于context,attributes object、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矩阵可能都是这样的:
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
Samples是一个dict{num=>;dict{num=>;dict{num=>;tuple(attributes,z\u matrix)}},具有一行z矩阵。你知道吗
你试过用词典理解吗?你知道吗
看这个great question about dictionary comperhansions
相关问题 更多 >
编程相关推荐