我试图操纵我的数据,我面临一些问题,我想你们中的一些人会知道如何这样做。你知道吗
首先,我把我的数据整理成这样:
data = [{'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'top', 'n' : 1, 'result' : 2.5} , {'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'top', 'n' : 2, 'result' : 3.8}, {'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'top', 'n' : 3, 'result' : 2.7}, {'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'bottom', 'n' : 1, 'result' : 34.2} , {'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'bottom', 'n' : 2, 'result' : 38.6}, {'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'bottom', 'n' : 3, 'result' : 27.3}]
如您所见,更改的值是方向、复制数和结果。你知道吗
我试图得到这个新的安排:
arrangeData = [{'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'top', n : [1,2,3], 'result' : [2.5, 3.8, 2.7]}, {'compound' : 'molecule1', 'time' : 18, 'temp' : 20, 'orientation' : 'bottom', n : [1,2,3], 'result' : [34.2, 38.6, 27.3]}]
正如你可能猜到的,我的dict的真实数据列表包含几个化合物、时间、温度
我第一个愚蠢的假设是在每个元素上循环:
for d in data:
if d[0] == 'molecule1':
if d[1] == 18:
if d[2] == 20
...
但这是硬编码和完全没有效率。你知道吗
然后,我尝试使用每个值的列表:
compound = ['molecule1', 'molecule2', 'molecule3]
time = [18, 24]
temp = [20, 37]
orientation = ['top', 'bottom']
然后再次循环每个列表:
for d in data:
for c in compound:
for t in time:
for tp in temp:
for o in orientation:
if d[0] == c:
...
同样愚蠢,因为所有的数据都在我的dict列表中,所以引入一个值列表似乎是一种错误的方式。你知道吗
以下是问题:
编辑1
谢谢,那正是我要找的!你知道吗
由于您只能有两个不同的方向值,因此此代码将无法正常工作。你知道吗
但是如果你有太多的变化,在这种情况下,这不是一个很好的解决方案。我宁愿列两份字典清单也不愿列两份清单。你知道吗
如果您愿意,可以选择一个更短的解决方案:
输出:
从
arrangeData
你举的例子来看,似乎你想把变量n和结果组合成化合物、时间、温度和方向。你知道吗我不打算为您编写代码,但请解释我将如何做到这一点。我会写两个循环。第一种方法创建一个字典,其中元组(复合、时间、温度和方向)作为键,值n和结果作为增长列表。然后在第二个循环中,我将把数据结构转换成arrangeData的dicts列表格式。你知道吗
似乎这是一个更大的代码库的一部分,也许你可以分享更多的上下文。可能有一个更简单的解决方案来达到你的目标。你知道吗
我假设对于这些数据行,您希望按(复合、时间、温度和方向)对它们进行分组。如果不是这样,你可以在下面修改我的代码。你知道吗
我们的想法是创建一个临时字典(out),其键是(compound、time、temp和orientation)的值,值是您所期望的:
代码如下:
相关问题 更多 >
编程相关推荐