【发布时间】:2018-01-31 06:42:40
【问题描述】:
我正在尝试比较列表元组中的元素并仅提取不常见但由于某种原因它返回整个组合的值。例如,如果我传递这样的值:
[(3,2), (2,4)]
那么它应该返回
[(3,4)]
这是我尝试过的:
a=[]
for i in range(len(l)):
j=i+1
for j in range(len(l)):
print(i)
print(j)
if l[i][0]==l[j][0]:
a.append((l[i][1],l[j][1]))
print(a)
elif l[i][0]==l[j][1]:
a.append((l[i][1],l[j][0]))
print(a)
elif l[i][1]==l[j][0]:
a.append((l[i][0],l[j][1]))
print(a)
elif l[i][1]==l[j][1]:
a.append((l[i][0],l[j][0]))
print(a)
我试图构建一个更通用的代码来处理不同类型的输入,但它无法处理所有情况。它为例如 [(3,2),(2,4)] 的单个比较提供了两种可能性。它同时提供 3 4 和 4 3 作为输出。
Sample inputs tried
>>onehop([(2,3),(1,2)]) input
>>[(1, 3)] expected output
>>onehop([(2,3),(1,2),(3,1),(1,3),(3,2),(2,4),(4,1)]) input
>>[(1, 2), (1, 3), (1, 4), (2, 1), (3, 2), (3, 4), (4, 2), (4, 3)] output
>>onehop([(1,2),(3,4),(5,6)]) input
>>[] expected output
>>onehop([(1,2),(2,1)]) input
>>[ ] expected output
>>onehop([(1,2)]) input
>>[ ] expected output
>>onehop([(1,3),(1,2),(2,3),(2,1),(3,2),(3,1)]) input
>>[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] expected output
是否有更优化的代码或列表理解可能。我是新手,正在学习这个 这是我尝试过的。
def onehop(l):
a = []
b = []
c = []
for i in range(len(l)):
j = i+1
for j in range(len(l)):
print(i) 'Just to understand the loops'
print(j)
if l[i][0] == l[j][1] and l[i][1] != l[j][0]:
a.append((l[i][1],l[j][0]))
elif l[i][0] != l[j][1] and l[i][1] == l[j][0]:
a.append((l[i][0],l[j][1]))
elif l[i][0] == l[j][0] and l[i][1] != l[j][1]:
a.append((l[i][1],l[j][1]))
elif l[i][0] != l[j][0] and l[i][1] == l[j][1]:
a.append((l[i][0],l[j][0]))
b = list(set(a))
b.sort()
return b
【问题讨论】:
-
提示:如果你使用集合,你可以大大简化这段代码。
-
例如,
tuple(set((3,2)).symmetric_difference(set((2,4))))产生(3, 4)。
标签: python python-3.x list tuples