简体   繁体   中英

How can I iterate the first element of each tuple in a list of tuples through a class method?

I am trying to determine if the first element meets a condition with an if statement, and if it does the next two items of the tuple will be inputted into the class method. so for example:

x = [(345, 1000, 5),(576, 1345, 8), (234, 1175, 3)]

In this instance I want to run the first element of the tuple, and if it means the condition, have the next two numbers be placed in the class method.

So far I have attempted to iterate by:

[i[0] for i in x]:
         if self.i >= 300 and self.i <=750:
              self.test1=[y[1] for y in x] 

I have learned this cannot be done, and I cannot seem to get around this issue.

After the condition is met the other two elements are supposed to be aggregated into two variable so I can take the average.


def regional_stats(self):

        [zipcode[0]for zipcode in all_data]:
            if self.zipcode >= 10000 and self.zipcode <= 14999:
                self.NY_sqft = [sqft[1] for sqft in all_data]
                self.NY_avgsqft = statistics.mean(square_footage)
                return self.NY_avg_sqft

I am working with housing data and need the zip codes to stay together with the square footage and bedrooms hence why I cannot simply extract them separately as their own variables. I am trying to aggregate the square footage and number of bedrooms if they are within this range of zip codes

While it's not entirely clear to me what you are trying to do, here is the basic syntax that should get you where you need to be.

In this case I just printed the average of the tuple that meets the conditions, however you can replace the print() with anything that suits you.

import numpy as np
x = [(345, 1000, 5),(576, 1345, 8), (234, 1175, 3)]

for t in x:
    if t[0] >= 300 and t[0] <= 750:
        print(np.mean(t))

Output

450.0
643.0

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