列表理解是一个很好的结构,用于以一种可以优雅地管理列表创建的方式来泛化使用列表。在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中优雅地做到这一点,任何让上面的代码更优雅的建议都会受到欢迎。
::编辑::
对于上下文,属性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,9Z矩阵可能都如下所示:
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.8672Samples是一个字典{num => dict{num => dict {num => =>(attributes,z_matrix)},具有一行z矩阵。
发布于 2013-11-26 16:26:48
列表理解是一个很好的结构,用来概括列表的工作,这样就可以优雅地管理列表的创建。在Python中有没有类似的工具来管理字典?
你有没有尝试过使用字典解释?
https://stackoverflow.com/questions/20208333
复制相似问题