我知道一些 c++ 的基础知识,但我是 python 的初学者。
我有一段工作代码(见下文),我想添加一个约束来格式化其输出,但我不知道该怎么做......
让我先解释一下程序的作用:
我有一个包含颜色列表的输入文件colors.csv
,一种颜色一行:颜色由它们的名称和色度坐标 X、Y 和 Z 定义,它看起来像这样:
Colorname, X1, Y1, Z1
Colorname2, X2, Y2, Z2
...etc.
给定包含在另一个输入文件中的任何 XYZ 坐标列表,targets.csv
程序将在输出文件中给我一个解决方案列表output.txt
该解决方案是通过首先用 tetgen 对点云进行三角剖分,然后是四面体中点的重心坐标来计算的,(但在这里解释一切并不重要......)
解决方案具有以下形式:
target, name0, density0, name1, density1, name2, density2, name3, density3
总是只有 4 个名称和相关的密度。
例如,它看起来像这样:
122 ,PINKwA,0.202566115168,GB,0.718785775317,PINK,0.0647284446787,TUwA,0.0139196648363
123 ,PINKwA,0.200786239192,GB,0.723766147717,PINK,0.0673550497794,TUwA,0.00809256331169
124 ,PINKwA,0.19900636349,GB,0.72874651935,PINK,0.0699816544755,TUwA,0.00226546268446
125 ,OR0A,0.00155317194109,PINK,0.0716160265958,PINKwA,0.195962072115,GB,0.730868729348
126 ,OR0A,0.00409427478508,PINK,0.0726192660009,PINKwA,0.192113520109,GB,0.731172939105
127 ,OR0A,0.00663537762906,PINK,0.073622505406,PINKwA,0.188264968103,GB,0.731477148862
我现在想做什么?
出于实际原因,我希望我的输出遵循一定的顺序。我想要一个“优先级列表”来控制name, density
输出的顺序。
我的实际程序以我不理解的顺序输出颜色名称,但无论如何我需要这些颜色名称按特定顺序排列,例如PINK
应该始终是第一个PINKwA
第二个等。
代替:
127 ,OR0A,0.00663537762906,PINK,0.073622505406,PINKwA,0.188264968103,GB,0.731477148862
我想;
127 ,PINK,0.073622505406,PINKwA,0.188264968103,OR0A,0.00663537762906,GB,0.731477148862
因为我的优先级列表说:
0, PINK
1, PINKwA
2, OR0A
3, GB
我怎样才能简单地将这个函数添加到下面的代码中?任何的想法?
编辑的代码(作品...):
import tetgen, geometry
from pprint import pprint
import random, csv
import numpy as np
from pprint import pprint
all_colors = [(name, float(X), float(Y), float(Z))
for name, X, Y, Z in csv.reader(open('colors.csv'))]
priority_list = {name: int(i)
for i, name in csv.reader(open('priority.csv'))}
# background is marked SUPPORT
support_i = [i for i, color in enumerate(all_colors) if color[0] == 'SUPPORT']
if len(support_i)>0:
support = np.array(all_colors[support_i[0]][1:])
del all_colors[support_i[0]]
else:
support = None
tg, hull_i = geometry.tetgen_of_hull([(X,Y,Z) for name, X, Y, Z in all_colors])
colors = [all_colors[i] for i in hull_i]
print ("thrown out: "
+ ", ".join(set(zip(*all_colors)[0]).difference(zip(*colors)[0])))
targets = [(name, float(X), float(Y), float(Z), float(BG))
for name, X, Y, Z, BG in csv.reader(open('targets.csv'))]
for target in targets:
name, X, Y, Z, BG = target
target_point = support + (np.array([X,Y,Z]) - support)/(1-BG)
tet_i, bcoords = geometry.containing_tet(tg, target_point)
output = open('output.txt','a')
if tet_i == None:
output.write(str(target[0]))
output.write('\n')
else:
names = [colors[i][0] for i in tg.tets[tet_i]]
sorted_indices = sorted(enumerate(names), key=lambda (i, name): priority_list[name])
output.write(target[0])
counting = 0
for i, name in sorted(enumerate(names), key=lambda (i, name): priority_list[name]):
output.write(',%s,%s' % (name, bcoords[i]))
counting = counting + 1
if counting > 3:
output.write('\n')
counting = 0
output.close()