首页 > 解决方案 > 计算 Python 列表中有多少对数字

问题描述

我四处搜索,发现如何在列表中返回多少对相同的值。例如:x = [10,10,20,30,20] => 它应该返回 2,因为我们有 2 对相同的值,每对:(10,10) 和 (20,20)。什么让我困惑并且不明白,为什么下面的函数返回结果 + 1?这会导致错误的输出。输出应该是 2,但我有 3!非常感谢。

x = [20, 30, 20, 30, 20, 40, 30]
freq = {} 
count = 0 
for item in x: 
  if (item in freq): 
     freq[item] += 1
  else:
    freq[item] = 1
for key, value in freq.items(): 
    count+=value/2 
print("Pairs : ",int(count))

标签: python-3.x

解决方案


以下代码行不是您要查找的内容:

set(ar).intersection(mylist)

它只是打印出列表中唯一元素的数量。

你可以做这样的事情:

freq = {}
count = 0 
for item in x: 
    if (item in freq): 
        freq[item] += 1
    else: 
        freq[item] = 1

for key, value in freq.items(): 
    count+=value/2
print("Pairs : ",count)

推荐阅读