Python C ++ adjacent list equivalent

2024-05-05 16:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我决定学Python。我有c++的背景,所以在Python方面我面临一些挑战。我的问题是:

我在C++中有以下语法,我在Python中寻找等价物。这只是一段代码。我不确定我是该用单子还是单子。你知道吗

int main()
{
    ...some code...

    int** matrix = 0;
    buildmatrix(vertices,matrix);

    ...some more code...
    return EXIT_SUCCESS;
}

void buildmatrix(int& vertices,int** &matrix)
{
    cout <<"Enter # of vertices -> ";
    cin >>vertices;

    matrix = new int* [vertices];       
    for(int i=0; i<vertices; i++)       
     {
      matrix[i] = new int[vertices];    
     }
     ...some more code...
}

简而言之,这将构建一个数组指针数组。让它看起来像矩阵。在将此代码转换为Python时使用的最佳数据结构和/或方法是什么?你知道吗


Tags: 代码newreturnmainmore语法codesome
3条回答

C++中的容器被限制为一种对象。std::vector<SomeType>只能包含SomeType类型的元素。std::list<SomeOtherType>只能包含SomeOtherType类型的元素。std::map<KeyType,ValueType>只能将类型为KeyType的键映射到类型为ValueType的值。等等。你知道吗

在python中不是这样的。mixed_up_list = ["a", 1, [2, 3, 4]]没有问题。python中的列表可以包含数字、字符串、元组、列表、dict、对象,简而言之,任何东西。如何在python中使用列表取决于您自己。注意我的mixed_up_list中的最后一个元素。这是一个python列表。您的邻接列表可以很容易地用Python列表来表示,而不需要用C++来处理所有的分配/解除分配。你知道吗

dict是其他语言可能称之为关联数组或哈希映射的东西。列表是任意长度的容器。如果需要数组的等价项,请使用列表。你知道吗

您应该做一个介绍性的Python教程;列表和数组之间的区别非常重要,将在这里进行解释。你知道吗

代码的Python翻译是:

def buildmatrix():
    vertices = int(raw_input("Enter # of vertices -> ")

    matrix = []      
    for i in range(vertices):
        matrix.append([])
    # alternatively, matrix = [[] for _ in range(vertices)]

    return vertices, matrix

def add_edge(matrix, vertex1, vertex2):
     matrix[vertex1].append(vertex2)
     matrix[vertex2].append(vertex1)

这是因为列表中的元素没有限制。在这里,每个元素是另一个列表,可以有任何长度。您可以随时更改列表的长度,我们在这里使用.append()执行此操作,因此您不需要在相邻列表中预先分配空间。你知道吗

相关问题 更多 >