python - 计算python中情侣列表的出现并将结果附加到新列表中,其中包含第一个列表中的所有元素
问题描述
我有这个:
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)),
]
我需要计算第一对出现了多少次
所以我这样做:
out = Counter((x[0]) for x in list)
输出:
Counter({('hash1', 'hash2'): 2, ('hash2', 'hash3'): 1, ('hash1', 'hash3'): 1, ('hash3', 'hash4'): 1, ('hash5', 'hash4'): 1})
没关系,但我想要的结果是这样的:
'hash1','hash2,(436,1403)
我需要第二个值,它可以是随机的,所以在这种情况下可以是
(436, 1403) or `(299, 1282))`
预期输出:
Couple of hash, any couple of number of the hash1,hash2, N.occurrences
((hash1,hash2),(436,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', '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))
输出:
('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))
推荐阅读
- regex - 正则表达式:阿拉伯语单词边界
- google-apps-script - Google Apps 脚本需要不受限制的范围
- python - 如何在 Python 中使用 QTextBrowser 而不是控制台?
- python - 如何像使用 Python 一样使用 SQL,通过复制行同时更改该行中的一个值,其中该值来自不同的列?
- python - Django:“详细信息”:“未找到。” 在网页上找不到 HTTP 404
- android - Flutter:前台通知在 Firebase 消息传递中不起作用
- linux-kernel - USB核心是否会负责释放urb->hcpriv,即使它不是自己分配的?
- javascript - 下面这段代码的初始化函数是什么?
- unity3d - 统一webgl中带有数组参数的SendMessage
- python - 接受文件并将参数从命令行传递给函数没有输出