Jup Jup - 1 year ago 97
Python Question

Comparing nested list Python

I guess the code will most easily explain what I'm going for...

list1 = [("1", "Item 1"), ("2", "Item 2"), ("3", "Item 3"), ("4", "Item 4")]
list2 = [("1", "Item 1"), ("2", "Item 2"), ("4", "Item 4")]

newlist = []

for i,j in list1:
if i not in list2[0]:
entry = (i,j)


if we call the nested tuples [i][j]

I want to compare the [i] but once this has been done I want to keep the corresponding [j] value.

I have found lots of information regarding nested tuples on the internet but most refer to finding a specific item.

I did recently use an expression below, which worked perfectly, this seems very similar, but it just won't play ball.

for i,j in highscores:
print("\tPlayer:\t", j, "\tScore: ", i)

Any help would be much apppreciated.

Answer Source

If I understand correctly from your comment you would like to take as newlist:

newlist = [("3", "Item 3")]

You can do this using list comprehension:

dif = [item for item in list1 if item not in list2]
newlist = list(dif)
print newlist

This will give you as a result:

[('3', 'Item 3')]

You could also use symmetric difference like:

L = set(list1).symmetric_difference(list2)
newlist = list(L)
print newlist

This will also give you the same result!

Finally you can use a lambda function like:

unique = lambda l1, l2: set(l1).difference(l2)
x = unique(list1, list2)
newlist = list(x)

This will also produce the same result!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download