如何根据两个列表获得自定义元组的计数

2024-10-06 03:59:28 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮助我在PYTHON中使用from collections import counter或任何其他最快的方法获取列表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的计数,每个元组的元素计数。你知道吗

抱歉伙计们希望你们能理解我的问题…再次抱歉我是新来的这条Python。你知道吗


Tags: 方法infromimport元素列表forcounter
2条回答

归功于@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)

好吧,我假设你想要什么作为你的输出,因为你不清楚。所以基本上你想要的是找到SS2中SS1中项的计数。你知道吗

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

也就是在(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]

相关问题 更多 >