Python 查找列表中的对数计数
我有一份数字清单:Python 查找列表中的对数计数,python,list,Python,List,我有一份数字清单: [5, 4, 3, 4, 2, 1, 3, 5, 3, 5, 3, 5,] 一对数字等于两个数字。例如,5出现4次,因此我们有2对5。在上面的列表中,我可以说我有5对。我希望输出计算列表中有多少对数字 我试过了,但是卡住了 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[ind
[5, 4, 3, 4, 2, 1, 3, 5, 3, 5, 3, 5,]
一对数字等于两个数字。例如,5出现4次,因此我们有2对5。在上面的列表中,我可以说我有5对。我希望输出计算列表中有多少对数字
我试过了,但是卡住了
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
实现这一点的更简单方法是使用as: 这里
Counter()
将生成一个dict
,其中数字作为键,列表中数字出现的次数作为其值。然后我迭代它的值,使用生成器表达式计算每个数字的对数,并使用sum()
对所有对数进行求和
有关详细信息,请参阅以下文档:
>>> 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