2

I have grandfathered a code which works has list:

A = [ 's1', 's2', 's3', 's1' ] #the actual size is about 200
B = [ 1, 2, 13, 4 ] #same size as A

s1, s2, s3 are variables defined on the fly as:

s1 = 5
s2 = 3
s3 = 13

I have a function defined as:

def fun1( s, arg2 ):
 return s * numpy.random.normal( 0, 1, ( 200, arg2 ) )

arg2 in above function comes from array B corresponding to s1 selected

I want to generate C such that:

C = [ fun1(s1,1), fun1(s2,2), fun1(s3,13), fun1(s1,4) ] #C can be list or collection of arrays, not sure about the best data structure for C
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
Zanam
  • 4,607
  • 13
  • 67
  • 143

2 Answers2

3

Use the built in function zip() to combine A and B into a list of tuples, before using a list comprehension:

import numpy as np

s1 = 5
s2 = 3
s3 = 13

A = ['s1', 's2', 's3', 's1']
B = [1, 2, 13, 4]

def fun1(s, arg2):
 return s * np.random.normal(0, 1, (200, arg2))

C = [fun1(locals()[A_item], B_item) for A_item, B_item in zip(A, B)]
gtlambert
  • 11,711
  • 2
  • 30
  • 48
  • I'd say `izip` instead of `zip`, otherwise +1 – Vlad Jan 14 '16 at 16:43
  • I haven't come across `izip` - is it more efficient? – gtlambert Jan 14 '16 at 16:43
  • 1
    [Depends](http://stackoverflow.com/questions/4989763/when-is-it-better-to-use-zip-instead-of-izip). `izip()` is the generator version, so it won't construct an actual list. Given you're passing it to the list comprehension, you don't need the actual zipped list, you'll be discarding it at the end anyway. – Vlad Jan 14 '16 at 16:45
  • `izip` doesn't even exist any more in modern Python (`zip` does what it used to). – DSM Jan 14 '16 at 16:52
  • 1
    @Vlad only is you are in python 2, in python 3 zip is the same as izip in 2 – Copperfield Jan 14 '16 at 17:28
  • Ah, I actually didn't know that. I knew they'd done this for `xrange` vs `range`, but I tend to use Python 2 more than I should. Sorry for the mixup. – Vlad Jan 14 '16 at 17:31
  • 1
    @Vlad in that case also know that they do the same with filter and map :) – Copperfield Jan 14 '16 at 17:37
  • That makes me happy! I always found having to import those awkward. – Vlad Jan 14 '16 at 17:39
2

Use locals()['s1'] to access the value of s1 given the string s1, if s1 is a local variable.

Use globals() if s1, s2...,s4 are global variables.

Idos
  • 15,053
  • 14
  • 60
  • 75
Tom Bennett
  • 2,305
  • 5
  • 24
  • 32