列表推导式是一个很好的结构,可以以一种可以优雅地管理列表创建的方式概括列表的工作。 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 中优雅地做到这一点,任何使上述代码更优雅的建议都将非常感激。
::编辑::
就上下文而言,属性对象、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
样本是一个 dict{num => dict {num => dict {num => tuple(attributes, z_matrix)}}},具有一行 z 矩阵。
最佳答案
The list comprehension is a great structure for generalising working with lists in such a way that the creation of lists can be managed elegantly. Is there a similar tool for managing Dictionaries in Python?
您尝试过使用字典理解吗?
关于python - 在 Python 中优雅地将排序推广到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208333/