Search code examples
pythonstringnumpystring-comparison

Comparing numpy.str to set that contains a single string


I have the following strings:

label1: 'Yes' (numpy string)

label2: 'Yes' (a set containing only a single string)

when I try to the comparisons label1 == label2 I get an error because label2 is a set, not a string.

When I try to the comparison label1 == label2[0] I get an error because "sets are not subscriptable".

Can someone help me see what I am missing?


Solution

  • Sets are un-ordered data structures, this means you can get value at any index i, this is cause only ordered structures could be indexed. In set, the order is different every time so indexing value at a particular element would give different results every time which would be pointless (that's why it isn't allowed)

    If you want to me make it work there are a number of ways.

    If you have single value:

    if label1 == list(label2)[0]:
        # Your code
    

    or

    if label1 == label2.pop():
        # Your code
    

    If You have multiple values:

    if label1 == sorted(list(label2))[INDEX_OF_YOUR_VALUE]:
        # Your code