首页 > 解决方案 > 避免 for 循环中的重复计数

问题描述

这是我的情况,我在一个列表中有 16 个元组。我需要匹配元组的元素之一并迭代列表。它应该返回给我唯一的集合,但它返回给我双倍或三倍的计数。对此有任何列表理解建议吗?

lst= [(12, 'a'), (15, 'a'), (17, 'a'), (12, 'a'), (15, 'a'), (23, 'b'), (12, 'b'), (18, 'b'), (12, 'b'), (12, 'b'), (15, 'a'), (12, 'a'), (15, 'a'), (15, 'a'), (24, 'c'), (12, 'c')]

我需要从上面访问这个列表,

for i in  employerEmployeeEdges:
""iterate over the list of tuples""
    for j in employerEmployeeEdges[1:]:
"""iterate over to the next tuple to check if that matches
        if i[1]==j[1]:
            print(i[1], j[1))

我知道我已经部分完成了匹配项目,但我将如何防止重复计算?

标签: python

解决方案


这将只给出唯一的元组:

import numpy as np
y = np.unique(lst, axis=0)
z = [] 
for i in y:
   z.append(tuple(i))

推荐阅读