Python - 通过自动化过程添加字典

时间:2012-12-31 10:49:43

标签: python dictionary

我正在写一个渗透程序,我检查两个坐标,如果它们在给定的半径内,我将它们添加到字典(字典中的列表,如果它有帮助),以显示它们已连接,通过以下内容:

def connected(x1,y1,x2,y2,radiusvalue):
    radius = ((x1-x2)**2 + (y1-y2)**2)**.5
    if radius <= radiusvalue:
                # Search pre-existing dictionaries
                # Create new dictionary and add (x1, y1) & (x2, y2)
                #   or add to pre existing dictionary containing either (x1, y1) 
                #   or (x2, y2)
    else:
        return False

但是,我坚持使用已注释掉的部分,主要是因为我不知道如何在没有d = {datahere}的情况下创建字典。如果不能做到这一点,我将如何去做我想做的事情?

感谢。

2 个答案:

答案 0 :(得分:0)

这是一个开始,但您没有准确说明算法的用途,因此这可能不是最有效的方法。

def add(pointdict,x1,y1,x2,y2):
    # If (x1,y1) isn't present yet, create an empty list of points
    if (x1,y1) not in pointdict:
        pointdict[(x1,y1)] = []
    # Add (x2,y2) to the list of points connected to (x1,y1)
    pointdict[(x1,y1)].append((x2,y2))

def connected(x1,y1,x2,y2,radiusvalue,pointdict):
    radius = ((x1-x2)**2 + (y1-y2)**2)**.5
    if radius <= radiusvalue:
        # Connect (x1,y1) to (x2,y2)
        add(pointdict,x1,y1,x2,y2)
        # Connect (x2,y2) to (x1,y1)
        add(pointdict,x2,y2,x1,y1)
        return True
    else:
        return False

答案 1 :(得分:0)

您不需要直接使用字典来解决此问题。

这个问题可以使用union找到数据结构直接解决,而不是字典。

相反,当你实现union-find时,你可以选择使用字典,但不仅如此。