Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

python - Find count of number of pairs in the list

I have list of numbers:

[5, 4, 3, 4, 2, 1, 3, 5, 3, 5, 3, 5,]

A pair of numbers is the same 2 numbers. For example, 5 occurs 4 times, so we have 2 pairs of 5s. In the list above I can say I have 5 pairs. I want the output to count how many pairs of numbers are in the list.

I tried this, but got stuck.

list = [5,4,3,4,2,1,3,5]
print(list)
temp = 0
new_list = []
for index,x in enumerate(list):
    elm_count = list.count(list[index])
    if new_list:
        for ind, y in enumerate(new_list):
            if list[index] == new_list[ind]:
                continue
                if not elm_count % 2:
                    occ_count = elm_count/2
                    temp += occ_count
                    new_list.append(list[index])
                    continue
question from:https://stackoverflow.com/questions/65857436/find-count-of-number-of-pairs-in-the-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simpler way to achieve this is using collections.Counter() with sum() as:

>>> my_list = [5, 4, 3, 4, 2, 1, 3, 5,3, 5, 3, 5,]

>>> sum(num//2 for num in Counter(my_list).values())
5

Here Counter() will generate a dict with number as key and count of occurrence of number in list as its value. Then I am iterating over its values and calculating the count of pairs for each number using generator expression, and doing summation on the count of all the pairs using sum().

You can refer below documents for more details:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...