如何将一个列表中的元组与同一列表中的其他元组进行比较,从而遍历元组列表?

时间:2017-11-15 20:35:13

标签: python list tuples networkx valuetuple

    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x) 

    print(check)

我基本上想检查每个列表(在列表中'检查')是否存在相同的元组,例如(1,3)和(3,1)。然后我想删除列表中的最后一个((3,1))'检查'。但是,该函数返回一个" list.remove(x):x不在列表中"我使用" check.remove(x)"时出错。当我使用" check.remove(y)"时,结果是:

output of "check.remove(y)"

我注意到第一个元组(具有相同值的元组)被删除,而在倒数第二个列表中,仍然存在一对具有相同值的元组。

How the list 'check' looks like

如何在同一列表中比较元组并删除包含相同值的第二个元组?

3 个答案:

答案 0 :(得分:2)

从列表中重复删除从来都不是一个好主意,因为它是O(N)。 但是,您可以在一个非嵌套的运行中进行清理。最好从头开始构建一个干净的列表,并可能将其重新分配给同一个变量:

seen, no_dupes = set(), []
for c in check:
    s = tuple(sorted(c))
    if s not in seen:
         seen.add(s)
         no_dupes.append(c)
# check[:] = no_dupes  # if you must

答案 1 :(得分:0)

使用in而非==

for x in check:
    this = sorted(x) #the first tuple
    for y in check:
        that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
        if this in that:
            check.remove(x) 
     # alternatively you might need to loop through this if its a tuple of tuples
     # for t in this:
     #     if t in that:
     #         check.remove(x)

print(check)

答案 2 :(得分:0)

考虑实例[(1,1), (1,1), (1,1)] 在第一次迭代中,x被分配给列表中的第一个元素,y也被分配给第一个元素,因为x=y,删除x。现在,当y迭代到第二个元素x=y时,现在x已经在上一次迭代中被删除了。你应该使用动态编程:

new_check = []
for x in check:
   this = sorted(x)
   if x not in new_check:
      new_check.append(x)
return new_check