get the count of elements of tuples of your own…not just the range or sequence

后端 未结 1 716
情深已故
情深已故 2020-12-22 12:42

The below code is running for first three elements of the tuple of this list

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


        
相关标签:
1条回答
  • 2020-12-22 13:45

    If what i understood from your question is correct, the code below will solve your issue:

    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)
    

    Output:

    (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
    
    0 讨论(0)
提交回复
热议问题