Home > front end >  Easier way to check if an item from one list of tuples doesn't exist in another list of tuples
Easier way to check if an item from one list of tuples doesn't exist in another list of tuples

Time:10-06

I have two lists of tuples, say,

list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple

Expected output: 'item4' # Item that doesn't exist in list2

As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?

CodePudding user response:

Assuming your tuple structure is exactly as shown above, this would work:

tuple(set(x[0] for x in list1) - set(x[0] for x in list2))

or per @don't talk just code, better as set comprehensions:

tuple({x[0] for x in list1} - {x[0] for x in list2})

result:

('item4',)

CodePudding user response:

This gives you {'item4'}:

next(zip(*list1)) - dict(list2).keys()

The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').

The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.

Try it online!

CodePudding user response:

This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.

list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []

OutputTuple = [(a) for a, b in list2]
for i in list1:
    if i in OutputTuple:
        pass
    else:
        not_in_tuple.append(i)

for i in not_in_tuple:
    print(i)

CodePudding user response:

You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:

items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))

Output:

>>> list3
[('item4',)]

CodePudding user response:

Try set.difference:

>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>> 

Or even better:

>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>> 

CodePudding user response:

that is a difference operation for sets:

set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)

output:

{'item4'}

CodePudding user response:

for i in list1:
  a=i[0]
  for j in list2:
      b=j[0]
      if a==b:
          break
  else:
      print(a)
  • Related