Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare multiple unique strings in a list

Edit: I am using Python 2.7

I have a given 'matrix' as shown below which contains multiple lists of strings. I want to sort through matrix and only print out the row(s) which only contain a specific set of strings.

Can any one give me a hint on how to go about this?

What I have tried so far:

matrix = [("One", "Two", "Three"),
("Four", "Five", "Six"),
("Seven", "Eight", "One"),
("Four", "Five", "Six"),
("One", "Three", "Six")]

for index, data in enumerate(matrix):
    if "One" and "Three" and "Six" in data:
        print data

desired output:

("One", "Three", "Six")

actual output(as of now):

('Four', 'Five', 'Six')
('Four', 'Five', 'Six')
('One', 'Three', 'Six')
like image 299
Hoser Avatar asked Aug 13 '26 02:08

Hoser


1 Answers

Your test is incorrect, you want to test each string separately with in:

if "One" in data and "Three" in data and "Six" in data:

and does not group operands for the in test; each component is evaluated separately:

("One") and ("Three") and ("Six" in data):

which leads to the result of "Six" in data being returned; the other two values are certainly always True as they are non-empty strings.

The better approach is to use a set:

if {"One", "Three", "Six"}.issubset(data):
like image 186
Martijn Pieters Avatar answered Aug 15 '26 16:08

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!