简体   繁体   中英

Python - Is it possible to create a list containing sets within it?

Is it possible to create a list containing sets within it?

This code is not compiling ( should I use a dictionary of sets instead? )

v = []

v.append(set(3, 2))

v[2] = set()

v[2].append(3, 1)

I am trying to do a graph traversal using a quasi Dijkstra's Algorithm. I am trying to store the adjacency list in sets within a list. Is this the right approach or should I use another data structure?

I am trying to convert the following C++ into Python. what data structure can I use for the Vector?

        long long leastTimeToInterview (int n, int k, int m)
    {
       vector<set<pair<int, int>>> v (n + 1); // first = time, second = stop #

       while (m--) {
          int i, j, t; cin >> i >> j >> t;
          v[i].insert ({ t, j });
          v[j].insert ({ t, i });
       }

       set<pair<int, int>> s ({ { 0,1 } });
       unordered_set<int> done;

set(3, 2)

That's not how you define a set. The set constructor only takes one argument.

Instead use:

v = []
v.append({3, 2})
print(v)

Output:

[{2, 3}]

As an alternative, you can pass any iterable to the set constructor:

set((3, 2))
set([3, 2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM