如何循环遍历元组列表,将一个列表中的元组与同一列表中的其他元组进行比较?
How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?
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)
我基本上想检查每个列表(在列表 'check' 中)是否存在相同的元组,例如 (1, 3) 和 (3, 1)。然后我想从列表 'check' 中删除最后一个 ((3,1))。但是,当我使用 "check.remove(x)" 时,函数 returns 出现 "list.remove(x): x not in list" 错误。当我使用 "check.remove(y)" 时,结果是:
output of "check.remove(y)"
我注意到第一个元组(具有相同值的元组)被删除,并且在倒数第二个列表中,仍然有一对具有相同值的元组。
How the list 'check' looks like
如何比较同一列表中的元组并删除包含相同值的第二个元组?
使用 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)
从列表中重复删除从来都不是一个好主意,因为它是 O(N)
。
但是,您可以在一个非嵌套 运行-through 中进行清理。最好从头开始构建一个干净的列表,并可能将其重新分配给同一个变量:
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,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 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)
我基本上想检查每个列表(在列表 'check' 中)是否存在相同的元组,例如 (1, 3) 和 (3, 1)。然后我想从列表 'check' 中删除最后一个 ((3,1))。但是,当我使用 "check.remove(x)" 时,函数 returns 出现 "list.remove(x): x not in list" 错误。当我使用 "check.remove(y)" 时,结果是:
output of "check.remove(y)"
我注意到第一个元组(具有相同值的元组)被删除,并且在倒数第二个列表中,仍然有一对具有相同值的元组。
How the list 'check' looks like
如何比较同一列表中的元组并删除包含相同值的第二个元组?
使用 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)
从列表中重复删除从来都不是一个好主意,因为它是 O(N)
。
但是,您可以在一个非嵌套 运行-through 中进行清理。最好从头开始构建一个干净的列表,并可能将其重新分配给同一个变量:
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,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