得到你自己的元组元素的数量...不仅仅是范围或序列

时间:2017-06-12 07:47:39

标签: python collections tuples counter slice

以下代码正在运行此列表元组的前三个元素

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)

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

,输出为:

(1, 2, 3) 3
(1, 2, 4) 1
(1, 3, 4) 1
(2, 3, 4) 1

但我的期望不仅仅是前三个元组...我想要元组(0,2,3)或元组(1,2,4)的计数器同样我可以通过元组的任意三个位置并得到它的计数......我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

如果我从您的问题中理解的是正确的,下面的代码将解决您的问题:

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, (0, 2, 4)))
elm_counter(elm)
print('---')
elm = list(get_new_list(SS1, (1, 2, 4)))
elm_counter(elm)

输出:

(1, 3, 5) 1
(1, 3, 6) 2
(1, 4, 6) 2
(2, 4, 6) 1
---
(2, 3, 6) 2
(2, 3, 5) 1
(3, 4, 6) 2
(2, 4, 6) 1