-1

I have this:

list = [
    (('hash1', 'hash2'), (436, 1403)),
    (('hash1', 'hash2'), (299, 1282)),
    (('hash2', 'hash3'), (1244, 30)),
    (('hash1', 'hash3'), (436, 1403)),
    (('hash3', 'hash4'), (299, 1282)),
    (('hash5', 'hash4'), (1244, 30)),
    ]

I need to count how many occurrences are for the 1st couple

So I do this:

out = Counter((x[0]) for x in list)

OUTPUT:

Counter({('hash1', 'hash2'): 2, ('hash2', 'hash3'): 1, ('hash1', 'hash3'): 1, ('hash3', 'hash4'): 1, ('hash5', 'hash4'): 1})

And it's okay, but the result I want is this:

'hash1','hash2,(436,1403)

I need the second value to, that can be random so in this case can be

(436, 1403) or `(299, 1282))`

EXPECTED OUTPUT:

Couple of hash, any couple of number of the hash1,hash2, N.occurrences
((hash1,hash2),(436,1403),2

There is a way to do this?

deadshot
  • 8,881
  • 4
  • 20
  • 39
CDixon
  • 21
  • 8
  • 1
    Which occurrences are you trying to count? your question is not clear and also your expected output – deadshot Aug 18 '20 at 09:19
  • The Couple of Hash but in the result i need the number for example 436, 1403.So for exaple "hash1" "hash2 , count 2 times, but i need to have in the final result "hash1,"hash2, 436,1403 , 2 like this – CDixon Aug 18 '20 at 09:21
  • 1
    can you update your expected output – deadshot Aug 18 '20 at 09:21

1 Answers1

2

You can use itertools.groupby and itertools.chain.from_iterable and random.choice

from itertools import groupby, chain
from random import choice

lst = [(('hash1', 'hash2'), (436, 1403)),
    (('hash1', 'hash2'), (299, 1282)),
    (('hash2', 'hash3'), (1244, 30)),
    (('hash1', 'hash3'), (436, 1403)),
    (('hash3', 'hash4'), (299, 1282)),
    (('hash5', 'hash4'), (1244, 30))]

for k, g in groupby(lst, lambda x: x[0]):
    g = list(chain.from_iterable(g))[1::2]
    print(k, choice(g), len(g))

Output:

('hash1', 'hash2') (299, 1282) 2
('hash2', 'hash3') (1244, 30) 1
('hash1', 'hash3') (436, 1403) 1
('hash3', 'hash4') (299, 1282) 1
('hash5', 'hash4') (1244, 30) 1

You can also use defaultdict

from random import choice
from collections import defaultdict

res = defaultdict(list)
for x in lst:
    res[x[0]].append(x[1])

for k, v in res.items():
    print(k, choice(v), len(v))
deadshot
  • 8,881
  • 4
  • 20
  • 39