Reputation: 43
How to check if list of tuples contains only tuples with elements ('name', 'surname', 'adress', 'car', 'colour') and ('name', 'surname', 'adress') tuple cannot exist with single 'car' and 'colour'
a =[
('name', 'surname', 'adres', 'car', 'colour'),
('name', 'surname', 'adres'),
('name', 'surname', 'adres', 'colour'),
('name', 'surname', 'adres', 'car')
]
for elem in a:
if 'car' not in elem and 'colour' not in elem:
print(elem)
below tuples are OK:
('name', 'surname', 'adres', 'car', 'colour')
('name', 'surname', 'adres')
Upvotes: 1
Views: 270
Reputation: 32928
In this case where you have such a small list of valid options, you could take the dead simple approach and just check if the tuple is one of them.
valid = {
('name', 'surname', 'adres', 'car', 'colour'),
('name', 'surname', 'adres')}
for elem in a:
if elem in valid:
print(elem)
If you want to do it algorithmically, then first you'll need to confirm that the tuple contains only the allowed elements, and contains neither or both of ('car', 'colour')
, which is XNOR.
allowed = {'name', 'surname', 'adres', 'car', 'colour'}
for elem in a:
if not all(x in allowed for x in elem):
continue
if ('car' in elem) ^ ('colour' in elem):
continue
print(elem)
(I broke it up to keep the lines under 80 chars)
Upvotes: 0
Reputation: 1230
You want to tackle this like a logic problem. You want either (a) you find both values in the tuple or (b) neither value in the tuple. You can almost code that expression into plain language like so:
def is_valid(t):
return ('car' in t and 'colour' in t) or ('car' not in t and 'colour' not in t)
Upvotes: 2