My input data is
[[1, 2], [3, 4], [5, 6], [1, 2, 7], [8, 2], [9, 5]]
My expected output is:
[[1, 2], [1, 2, 7], [8, 2], [3, 4], [5, 6], [9, 5]]
With the help of How to compare each item in a list with the rest, only once? currently my snippet looks like
mylist = [[1, 2], [3, 4], [5, 6], [1, 2, 7], [8, 2], [9, 5]]
result = list()
for i in range(len(mylist)):
result.append(mylist[i])
for j in range(i + 1, len(mylist)):
if set(mylist[i]) & set(mylist[j]):
result.append(mylist[j])
mylist.remove(mylist[j])
print(result)
However, It is throwing error IndexError: list index out of range
. I guess this is because I am trying to remove items from a list while iterating.
So I checked How to remove items from a list while iterating?. It suggested using slice or itertools. It also gave a code snippet which I found much more readable.
temp = []
while somelist:
x = somelist.pop()
if not determine(x):
temp.append(x)
while temp:
somelist.append(templist.pop())
However, I could not figure out how it might work. Any idea?
Update 1
Snippet:
mylist = [[1, 2], [3, 4], [5, 6], [1, 2, 7], [8, 2], [9, 5]]
result = list()
for i in range(len(mylist)):
result.append(mylist[i])
for j in range(i + 1, len(mylist)):
if set(mylist[i]) & set(mylist[j]):
result.append(mylist[j])
# mylist.remove(mylist[j])
print(result)
Output:
[[1, 2], [1, 2, 7], [8, 2], [3, 4], [5, 6], [9, 5], [1, 2, 7], [8, 2], [8, 2], [9, 5]]
I do not want [1, 2, 7], [8, 2], [8, 2], [9, 5]
in the result so I trying to use mylist.remove(mylist[j])
, which I could not figure out how to do.