如何解决计算python中对子列表的出现并将结果与第一个列表中的所有元素一起追加到新列表中
我有这个:
list = [
(('hash1','hash2'),(436,1403)),(('hash1',(299,1282)),(('hash2','hash3'),(1244,30)),(('hash3','hash4'),(('hash5',]
我需要计算第一对夫妇发生了多少次
所以我这样做:
out = Counter((x[0]) for x in list)
输出:
Counter({('hash1','hash2'): 2,('hash2','hash3'): 1,('hash1',('hash3','hash4'): 1,('hash5','hash4'): 1})
没关系,但是我想要的结果是这样:
'hash1','hash2,1403)
我需要第二个值,该值可以是随机的,因此在这种情况下可以是
(436,1403) or `(299,1282))`
期望的输出:
Couple of hash,any couple of number of the hash1,hash2,N.occurrences
((hash1,hash2),1403),2
有办法做到吗?
解决方法
您可以使用itertools.groupby和 itertools.chain.from_iterable和random.choice
from itertools import groupby,chain
from random import choice
lst = [(('hash1','hash2'),(436,1403)),(('hash1',(299,1282)),(('hash2','hash3'),(1244,30)),(('hash3','hash4'),(('hash5',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))
输出:
('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
您也可以使用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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。