Search code examples
python-3.xlistobjectiteratorinstance

How to pass list of tuples through a object method in python


Having this frustrating issue where i want to pass through the tuples in the following list through a method on another list of instances of a class that i have created

list_1=[(0, 20), (10, 1), (0, 1), (0, 10), (5, 5), (10, 50)]
instances=[instance[0], instance[1],...instance[n]]
results=[]
pos_list=[]
for i in range(len(list_1)):
    a,b=List_1[i]
    result=sum(instance.method(a,b) for instance in instances)
    results.append(result)
    if result>=0:
        pos_list.append((a,b))
print(results)
print(pos_list)

the issue is that all instances are taking the same tuple, where as i want the method on the first instance to take the first tuple and so on. I ultimately want to see it append to the new list (pos_list) if the sum is >0.

Anyone know how i can iterate this properly?


EDIT It will make it clearer if I print the result of the sum also.

Basically I want the sum to perform as follows:

result = instance[0].method(0,20), instance[1].method(10,1), instance[2].method(0,1), instance[3].method(0,10), instance[4].method(5,5), instance[5].method(10,50)

For info the method is just the +/- product of the two values depending on the attributes of the instance. So results for above would be:

result = [0*20 - 10*1 - 0*1 + 0*10 - 5*5 + 10*50] = [465]
pos_list=[(0, 20), (10, 1), (0, 1), (0, 10), (5, 5), (10, 50)]

except what is actually doing is using the same tuple for all instances like this:

result = instance[0].method(0,20), instance[1].method(0,20), instance[2].method(0,20), instance[3].method(0,20), instance[4].method(0,20), instance[5].method(0,20)
result = [0*20 - 0*20 - 0*20 + 0*20 - 0*20 + 0*20] = [0]
pos_list=[]

and so on for (10,1) etc.

How do I make it work like the first example?


Solution

  • many thanks for the above! I have it working now. Wasn't able to use args given my method had a bit more to it but the use of zip is what made it click

    import random
    rand=random.choices(list_1, k=len(instances))
    
    results=[]
    pos_list=[]
    for r in rand:
        x,y=r
    result=sum(instance.method(x,y) for instance,(x,y) in zip(instances, rand))
    results.append(result)
    if result>=0:
        pos_list.append(rand)
    print(results)
    print(pos_list)
    

    for list of e.g.

    rand=[(20, 5), (0, 2), (0, 100), (2, 50), (5, 10), (50, 100)]
    

    this returns the following

    results=[147]
    pos_list=[(20, 5), (0, 2), (0, 100), (2, 50), (5, 10), (50, 100)]
    

    so exactly what I wanted. Thanks again!