Python: Is there a better way to combine the values of a list -
this question has answer here:
i'm doing little project class @ university. in 1 of functions have list, like:
x = ["q0", "q1", "q2", "q3", "q4"]
what want list create dictionary, i'll use store values , values searching in matrix, combine values of list, this:
dic = {("q0", "q1"): "", ("q0", "q2"): "", ... ("q3", "q4"): ""}
i did way:
part1 = x[1:] part2 = x[:-1] dic = {} v in part1: r in part2: if v != r , (r, v) not in dic.keys(): dic[(v, r)] = ""
i used if because don't want repeated values, like:
("q1", "q1")
and don't want opposed values, like:
("q2", "q3"), ("q3", "q2")
my question if there better way of doing this. better using inside for. (when better mean faster) , if there isn't better way, wonder if there more clean way write code. maybe using list comprehension.
you can use itertools.combinations
within dict comprehension :
>>> itertools import combinations >>> x = ["q0", "q1", "q2", "q3", "q4"] >>> d={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'): ''}
Comments
Post a Comment