Feb-27-2021, 06:09 PM
(This post was last modified: Feb-27-2021, 06:13 PM by deanhystad.)
Cheating with formatting. Sets are awkward to use in something like this. How do you get the count out of the set? A dictionary is a much better fit, and a counting dictionary does all the work. Just pretty up the output if required.
from collections import Counter groups=[ ["word1", "word2"], ["word1", "word2","word1"], ["word4", "word5","word4", "word5", "word2", "word3"]] out = Counter([(a,b) for group in groups for a, b in zip(group, group[1:])]) pairs = ', '.join(f'{{"{key[0]}", "{key[1]}", {value}}}' for key, value in out.items()) print(f'out = [{pairs}]')
Output:out = [{"word1", "word2", 2}, {"word2", "word1", 1}, {"word4", "word5", 2}, {"word5", "word4", 1}, {"word5", "word2", 1}, {"word2", "word3", 1}]