Python: Is there a better way to combine the values of a list

64 Views Asked by At

I'm doing a little project for some class at my university. In one of my functions I have a list, like:

x = ["q0", "q1", "q2", "q3", "q4"]

What I want from that list is to create a dictionary, that I'll use to store values and then get the values like i was searching in a matrix, that combine the values of the list, like this:

dic = {("q0", "q1"): "", ("q0", "q2"): "", ... ("q3", "q4"): ""}

I did it this way:

part1 = x[1:]
part2 = x[:-1]
dic = {}
for v in part1:
    for r in part2:
        if v != r and (r, v) not in dic.keys():
            dic[(v, r)] = ""

I used a if because i don't want repeated values, like:

("q1", "q1")

And I also don't want opposed values, like:

("q2", "q3"), ("q3", "q2")

My question is if there is a better way of doing this. Better than using a for inside a for. (When I say better I mean faster) And if there isn't a better way, I wonder if there is a more clean way to write this code. Maybe using list comprehension.

1

There are 1 best solutions below

0
On

You can use itertools.combinations within a dict comprehension :

>>> from itertools import combinations 
>>> x = ["q0", "q1", "q2", "q3", "q4"]
>>> d={i:'' for i in combinations(x,2)}
>>> d
{('q0', 'q3'): '', ('q2', 'q3'): '', ('q0', 'q2'): '', ('q3', 'q4'): '', ('q1', 'q3'): '', ('q0', 'q4'): '', ('q1', 'q4'): '', ('q0', 'q1'): '', ('q1', 'q2'): '', ('q2', 'q4'): ''}