【问题标题】:How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?如何遍历元组列表,将一个列表中的元组与同一列表中的其他元组进行比较?
【发布时间】:2023-04-04 03:35:01
【问题描述】:
    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))。但是,当我使用“check.remove(x)”时,该函数会返回“list.remove(x): x not in list”错误。当我使用“check.remove(y)”时,结果是:

output of "check.remove(y)"

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

How the list 'check' looks like

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

【问题讨论】:

    标签: python list tuples networkx valuetuple


    【解决方案1】:

    从列表中重复删除绝不是一个好主意,因为它是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
    

    【讨论】:

    • 我试图在我的函数中实现代码,但得到这个错误:“unhashable type: 'list'”。是不是我实施错了?
    【解决方案2】:

    使用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)
    

    【讨论】:

      【解决方案3】:

      考虑实例[(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
      

      【讨论】:

      • 它适用于列表“检查”中的第一个列表,但它不显示其余列表。也许是因为回报?因为 for 循环然后停止(所以它只适用于列表“检查”中的第一个列表)?
      • 是的,取出退货
      猜你喜欢
      • 2021-01-23
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多