PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] how to avoid append many times?

 May 13, 2022     append, list, loops, python     No comments   

Issue

I have a piece of code which involves many append command,

 items = [a1,a2,a3,a4,a5,a6,a7]
 A_all = []
 for t in range(len(items)):
     A_BS = []
     for i in range(iter):
         idx_BS = np.random.choice(np.shape(items[0])[1], boots)
         corr_atra = get_corr((items[t][:,idx_BS]).T)
         A_BS.append(np.mean(corr_atra))
 A_all.append(np.mean(A_BS)) 

what the code do is that for each data set a_i bootstrap among columns and compute the correlation and then get the average there. Is there a way to avoid some of these appends?


Solution

You could pack it into list comprehensions:

s = np.shape(items[0])[1]
A_all = [
    [
        np.mean(get_corr(item[:, np.random.choice(s, boots)].T))
        for _ in range(iter)
    ]
    for item in items
]

But: Whatever iter is should have another name because iter is a built-in function.

You don't use i - is that intensional?



Answered By - Timus
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing