如何针对两个列表获取自定义元组的计数

时间:2017-06-12 05:10:36

标签: python tuples counter slice iterable

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

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)个元素的计数

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元素计算每个元组。

对不起,小伙伴们希望你能理解我的问题......对不起,我是新来的这个蟒蛇。

2 个答案:

答案 0 :(得分:0)

好的,我在这里假设您想要的输出,因为您不清楚。所以基本上你想要的是在SS2中的SS1中找到项目的数量。

e.g。 SS1中出现(1,4,5)的次数

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)

我认为你可能需要的是。

set(tuple2).issubset(tuple1)

所以这是您的问题的代码:

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中每个项目的计数列表:

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

答案 1 :(得分:-1)

归功于@Chiheb Nexus

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

def get_new_list(a, pos):
    # Check if any element in pos is > than the length of the tuples
    if any(k >= len(min(SS1, key=lambda x: len(x))) for k in pos):
        return

    for k in a:
        yield tuple(k[j] for j in pos)

def elm_counter(elm):
    if not len(elm):
        return 

    c = Counter(elm)
    for k, v in c.items():
        if v > 0:
            print(k, v)
elm = list(get_new_list(SS1, (2,)))
elm_counter(elm)
print('---')    
elm = list(get_new_list(SS1, (0, 2, 3)))
elm_counter(elm)
print('---')
elm = list(get_new_list(SS1, (1, 3, 4)))
elm_counter(elm)