简体   繁体   中英

How would I be able to return which instance belongs to the random number in my list. Without using a million if statements?

what I am trying to do, is return the instance, which range has the value from a random.randint() in a list.... Example...

class Testing:

    def __init__(self, name, value):

        self.name = name
        self.value = value

randomtest = Testing('First', range(1, 50))
randomtest_2 = Testing('Second', range(50, 100))

selections = []
counter = 0

while counter < 2:
    counter =+ 1

    selector = random.randint(1, 100)
    selections.append(selector)

But I don't want to use a million if statements to determine which index in the selections list it belongs to.. Like this:

if selections[0] in list(randomtest.value):
    return True

elif selections[0] in list(randomtest_2.value):
    return True

Your help is much appreciated, I am fairly new to programming and my head has just come to a stand still at the moment.

You can use a set for your selections object then check the intersection with set.intersection() method:

ex:

In [84]: a = {1, 2}

In [85]: a.intersection(range(4))
Out[85]: {1, 2}

and in your code:

if selections.intersection(randomtest.value):
    return True

You can also define a hase_intersect method for your Testing class, in order to cehck if an iterable object has intersection with your obejct:

class Testing:

    def __init__(self, name, value):
        self.name = name
        self.value = value

    def hase_intersect(self, iterable):
        iterable = set(iterable)
        return any(i in iterable for i in self.value)

And check like this:

if randomtest.hase_intersect(selections):
    return True

based on your comment, if you want to check the intersection of a spesific list against a set of objects you have to iterate over the set of objects and check the intersection using aforementioned methods. But if you want to refuse iterating over the list of objects you should probably use a base claas with an special method that returns your desire output but still you need to use an iteration to fild the name of all intended instances. Thus, if you certainly want to create different objects you neend to at least use 1 iteration for this task.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM