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)
newlist.append(entry)
print(newlist)
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.
If I understand correctly from your comment you would like to take as newlist:
newlist = [("3", "Item 3")]
You can do this using:
1) list comprehension:
newlist = [item for item in list1 if item not in list2]
print newlist
This will give you as a result:
[('3', 'Item 3')]
2) 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!
3) 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!
4) Oh, and last but not least, using simple set properties:
newlist = list((set(list1)-set(list2)))
I think you just want to create a set of the first elements of list2, if you're only looking to compare the first element of the lists.
newlist = []
list2_keys = set(elem[0] for elem in list2)
for entry in list1:
if entry[0] not in list2_keys:
newlist.append(entry)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.