避免在for循环中重复计算

时间:2018-10-14 00:21:48

标签: python

这是我的情况,列表中有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))

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

2 个答案:

答案 0 :(得分:0)

不确定您要从问题中得到什么输出,但是我将这样解释:

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')]

unique_ele = set([l[1] for l in lst])
summed_tuples = [(sum([l[0] for l in lst if l[1] == ele]), ele) for ele in unique_ele]  # [(77, 'b'), (36, 'c'), (128, 'a')]

答案 1 :(得分:0)

这将只给出唯一的元组:

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