简体   繁体   中英

How can I turn the results of a for loop into a list?

How can I alter this for loop to turn it into a list? Thanks in advance.

for x in column_list:
    des, res=rp.ttest(group1= df[x][df['patients'] == 1], group1_name= "Patients",
         group2= df[x][df['patients'] == 0], group2_name= "Controls")
    res1=res.set_index('Independent t-test').T
    y=res1['Two side test p value = '].values
    if y < 0.005:
        print (x,y)

I recall your previous question. I think something like the following may help:

outputList = []
for x in column_list:
    des, res=rp.ttest(group1= df[x][df['patients'] == 1], group1_name= "Patients",
         group2= df[x][df['patients'] == 0], group2_name= "Controls")
    res1=res.set_index('Independent t-test').T
    y=res1['Two side test p value = '].values
    
    #collect the values into a dictionary and append that dictionary to the outputList
    outputList.append({"x":x, "y":y})

#Now loop the list and only print the ones with appropriate p-level
for pair in outputList:
    if pair["y"] < 0.005:
        print (pair["x"],pair["y"])

This is moving the print() down into a new section of code after all of the x,y pairs have been collected into a list. Using a dictionary makes this all a bit cleaner.

If you want to see whats going on, you can toss print(outputList) before that second for loop and see what that output looks like. It may help connect the dots.

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