0

I have the following function that resamples 100 times a file of ~800 elements:

def resample(arg_array):
    all_sets = []
    i = 1
    while i <= 100:
        subset = np.random.choice(arg_array, 100, replace=True)
        all_sets.append(subset)
        i += 1
    return all_sets

This produces a list of arrays with 100 elements each, stored in all_sets.

I need to split this list and save each array into a new variable. Thought about doing list comprehension, but doing set1, set2, ..., set100 = [list comprehension] just doesn't seem very efficient or elegant at all.

Would be great if Python had something like bash where you can generate a new variable name for each pass in a loop.

4
  • You could make a class and make each set an attribute of that class using setattr() But I'd be surprised if you really need to do that rather than just accessing the list elements by their index. Can you expand a bit more on the use case? Commented Feb 25, 2021 at 2:51
  • This is basically for a jackknife analysis. Have about 700 (not 800) IDs from which to resample and do my tests against 100 controls. Repeat 100 times. Since my stuff is done on the shell, I would like to pass a command line argument (txt file with the IDs) as the function argument, and then output the new 100-element resampled lists to new txt files that I can work on downstream. Commented Feb 25, 2021 at 3:40
  • Unpacking from a list or tuple is the only reasonable python code. 'dynamically' creating variable names is awkward and distinctly un-pythonic. Use lists and dicts if you need to work with many objects. Commented Feb 25, 2021 at 7:22
  • I guess I could do a loop and write each element in the list or dict in a new file, but the globals() solution worked as well. Commented Feb 25, 2021 at 22:53

2 Answers 2

1

How about like this?

def resample(arg_array):
    for i in range(1, 101):
        subset = np.random.choice(arg_array, 100, replace=True)
        globals()[f"set{i}"] = subset
Sign up to request clarification or add additional context in comments.

1 Comment

That worked for what I need. I used that to write each subset into a new file, which is exactly what I wanted. Thanks.
1

Instead of creating a variable for each set you could store them in a dictionary like this.

def resample(arg_array):
    sample_map = {}
    for n in range(1, 100+1):
        subset = np.random.choice(arg_array, 100, replace=True)
        sample_map[n] = subset
    return sample_map

Or even this

def resample(arg_array):
    sample_map = {n:np.random.choice(arg_array, 100, replace=True) for n in range(1, 100+1)}
    return sample_map

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.