我有一个坐标为100点的文本文件,属于一些抛物线。每个点由具有以下结构的行描述:X_coordinate
,Y_coordinate
,ID
,next_ID
,tag
。
ID
是行号,next_ID
是沿某个抛物线所考虑的点之后的点的ID。通常,next_ID != ID + 1
。我希望我的脚本能够给出某个抛物线的所有点tag
;你有什么建议怎么做吗?
输入文件看起来像
23.009 784.343 1 22
472.844 387.843 2 0
32.899 209.027 3 23
345.283 294.034 4 24
[...]
48.939 778.283 22 35
我想要做的是添加一个标记列,以便
23.009 784.343 1 22 1
472.844 387.843 2 0 0
32.899 209.027 3 23 2
345.283 294.034 4 24 3
[...]
48.939 778.283 22 35 1
下面你可以找到我提出的代码。如果可能的话,我想使用更加pythonic的解决方案; - )
for i in range(0, Number_of_lines_in_txt):
if next_ID[i] != 0: # I check that the considered point has a following one along
# The considered parabola
if tag[i] == 0: # If the point is already tagged, we skip it
tag = tag + 1
tag[i] = tag
# Now we do the same for next_ID: we check if it has a following point,
# We check if it has a tag.
if next_ID[next_ID[i]] != 0:
if tag[next_ID[i]] == 0:
tag[next_ID[i]] == tag
# Third iteration
if next_ID[next_ID[next_ID[i]]] != 0
[...]
答案 0 :(得分:0)
所以看起来你想要做的是创建一个Point
类,然后创建一个Point
对象列表,并带有一些默认标记。最后,您需要在列表上执行深度优先搜索以创建标记。然后,您希望将Point
写回文件,最好是为每个__repr__
编写Point
函数。
类似(未经测试,在答案框中写到)
class Point():
tag = 0
def __init__(self, xCoord, yCoord, id, nextID):
self.xCoord = xCoord
self.yCoord = yCoord
self.id = id
self.nextID = nextID
def __repr__(self):
return "%f %f %d %d %d" % (xCoord, yCoord, id, nextID, tag)
"""do some file I/O, call readlines() to fill a list named lines"""
pointDictionary = {}
for line in lines:
col = line.split()
point = Point(float(col[0]), float(col[1]), int(col[2]), int(col[3]))
pointDictionary[point] = False #unvisited for our DFS
#DFS
def DFS(nextPoint, pointDict, tag): #DFS from this point, setting all to same tag
if pointDict[nextPoint] == True:
return
pointDict[nextPoint] = True
nextPoint.tag = tag
DFS(pointDict[nextPoint.nextID-1], pointDict, tag) #assuming IDs are from 1...n
tag = -1
for point in pointDictionary:
if pointDictionary[point] == False:
tag += 1
DFS(point, pointDictionary, tag)
"""Now some I/O to simply write contents of
pointDictionary (keys only) to an output file"""
编辑:我仍然不完全理解您分配标签的逻辑。我将遍历通过nextID
s连接的所有点,并从0开始为它们分配标签。我假设这些点是有序的,这样可以通过遍历nextID
s <到达抛物线中的所有点/ p>