问题
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)]
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)
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.
Sorry guys hope you understand my question...sorry again i'm new this python.
回答1:
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.
e.g. The number of times (1,4,5)
occuring in SS1
Which would be 3 i.e in (1, 2, 3, 4, 5)
,(1, 2, 4, 5, 6)
,(1, 3, 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)
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]
回答2:
credit to @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)
来源:https://stackoverflow.com/questions/44491784/how-to-get-the-count-of-custom-tuples-against-two-lists