Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension inside dictionary comprehension - scope

I am trying to create a complete graph in a Python Dictionary in 1 line. But when creating the list comprehension for the values I can not figure out how to specify that the key_value can not appear in the list of values (in graph speak, no self loop).

for n nodes

G = {k:[v for v in range(n)] for k in range(n) }

results in this (example n = 3)

{0: [0, 1, 2], 1: [0, 1, 2], 2: [0, 1, 2]}

but what I want is this

{0: [1, 2], 1: [0, 2], 2: [0, 1]}

But trying something similar to this

G = {k:[v for v in range(n) for v !=k] for k in range(n) }

will throw an error at the k in the list comprehension. So k must be out of scope for the list comprehension, which makes sense.

Can G be defined in this method?

like image 662
Max Wen Avatar asked Sep 28 '22 17:09

Max Wen


1 Answers

To ignore the key's value from the value list, you just have to put a validation in your list comprehension.

G = { k: [v for v in range(n) if v != k] for k in range(n) }

So for n = 3 you graph G would return :-

{0: [1, 2], 1: [0, 2], 2: [0, 1]}
like image 185
Tanveer Alam Avatar answered Nov 06 '22 13:11

Tanveer Alam