📜  Python - 列表中的总相等对

📅  最后修改于: 2022-05-13 01:54:57.533000             🧑  作者: Mango

Python - 列表中的总相等对

给定一个列表,任务是编写一个Python程序来计算总等位数对,即提取所有元素的数量,可以与列表中存在的相似元素进行双重配对。

Input : test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3]
Output : 4

Explanation : 4, 2 and 5 have 3 occurrences, 7 has 2 occurrences, 1 pair each.

Input : test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3, 3]
Output : 5

Explanation : 4, 2 and 5 have 3 occurrences, 1 pair each and 3, 7 have 2 occurrences, total 5 pairs.

方法#1:使用count() + set()

在此,我们将容器转换为 set 并在原始列表中的每个元素上使用count() 。获得与 2 的商并求和以获得所需的对。

Python3
# Python3 code to demonstrate working of
# Total equal pairs in List
# Using loop + count()
  
# initializing lists
test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
all_ele = set(test_list)
res = 0
for ele in all_ele:
  
    # summing count from element list
    res += test_list.count(ele) // 2
  
# printing result
print("Total Pairs : " + str(res))


Python3
# Python3 code to demonstrate working of
# Total equal pairs in List
# Using Counter() + list comprehension + sum()
from collections import Counter
  
# initializing lists
test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using Counter for getting elements count
res = sum(ele // 2 for ele in Counter(test_list).values())
  
# printing result
print("Total Pairs : " + str(res))


输出:

The original list is : [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3]
Total Pairs : 4

方法#2:使用 Counter() +列表推导+ sum()

在这种情况下,使用Counter()获取每个元素的计数, sum()用于计算总对。

蟒蛇3

# Python3 code to demonstrate working of
# Total equal pairs in List
# Using Counter() + list comprehension + sum()
from collections import Counter
  
# initializing lists
test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using Counter for getting elements count
res = sum(ele // 2 for ele in Counter(test_list).values())
  
# printing result
print("Total Pairs : " + str(res))

输出:

The original list is : [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3]
Total Pairs : 4