如何获取针对两个列表的自定义元组的计数 [英] How to get the count of Custom tuples against two lists

查看:85
本文介绍了如何获取针对两个列表的自定义元组的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我获取PYTHON中列表SS1中列表SS2的计数器,方法是使用集合导入计数器或任何其他最快的方式

Please help me to get the counter for the list SS2 in list SS1 in PYTHON using from collections import Counter or any other fastest way

SS1 = [(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]

SS2=[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 4), (1, 3, 5), (1, 3, 6), (1, 4, 5),
(1, 4, 6), (1, 5, 6), (2, 3, 4), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6),
(3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]

这是我尝试过的但我不知道如何获得每个元组的第(1,2,4)个元素的计数

Here is what i have tried and i don't know how to get the count for (1,2,4) th elements of the each tuple

SS1=[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]

from collections import Counter
c = Counter(elem[0:3] for elem in SS1[0:6])

for k, v in c.items():
    if (v > 0):
        print(k,v)

现在,这对于0:3来说是完美的运行方式,但是我要获得的不是1,2,3的计数,而是我想要1,2,4的每个元组的元素计数。

Now this is running perfect for 0:3 but what i want is to get the count for not 1,2,3 but i want for 1,2,4 the elements count for each tuple.

对不起,希望您能理解我的问题...对不起,我是这个Python新手。

Sorry guys hope you understand my question...sorry again i'm new this python.

推荐答案

好吧,我不确定您想要什么,因为您不清楚。因此,基本上,您想要的是在SS2的SS1中找到 个计数。

Ok I am assuming what you want as your output here as you weren't clear. So basically what you want is to find the count of items in SS1 in SS2.

例如在SS1中(1,4,5)发生的次数

e.g. The number of times (1,4,5) occuring in SS1

其中 3 ,即(1、2、3、4、5)(1、2、4、5、6)(1、3、4、5、6)

所以(1、2、5)会再次是 3 吧?存在于
(1、2、3、4、5),(1、2、3、5、6),(1、2、4、5、6)

so for (1, 2, 5) it would be 3 again right? present in (1, 2, 3, 4, 5),(1, 2, 3, 5, 6),(1, 2, 4, 5, 6)

我认为您可能需要的是。

I think what you might need is.

set(tuple2).issubset(tuple1)

这是您遇到的问题的代码:

So here is a code for your problem:

SS1 = [(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]
SS2=[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 4), (1, 3, 5), (1, 3, 6), (1, 4, 5),
(1, 4, 6), (1, 5, 6), (2, 3, 4), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6), (2, 5, 6),
(3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]
count=0
count_list = []
for ss2item in SS2:
    for ss1item in SS1:
        if set(ss2item).issubset(ss1item):
            count+=1
    count_list.append(count)        
    count=0
print(count_list)

其输出将是SS2中每个项目的计数列表:

It's output would be a list of count for each items in SS2:

[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

这篇关于如何获取针对两个列表的自定义元组的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆