2

I have the following code in python 3:

x = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(5)]

Is there a better way to initialize multiple (5+) lists with different K values and in range()?

ex:

y = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
z = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(2)]
a = [(''.join(random.choices(string.ascii_lowercase, k=4))) for _ in range(3)]
b = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
c = [(''.join(random.choices(string.ascii_lowercase, k=1))) for _ in range(3)]
1
  • generate the lists in a loop and append to another list which is declared before the loop Commented Jul 7, 2017 at 19:09

2 Answers 2

5

Put the list comprehension in a function and use that repeatedly:

def func(k, r):
   return [(''.join(random.choices(string.ascii_lowercase, k=k))) for _ in range(r)]

y = func(3, 5)
...
c = func(1, 3)

If you have the values of k and r in two lists, you can do:

y,..., c =  (func(*t) for t in zip(lst_k, lst_r))

Or better still keep the data structure as a list of lists to not worry about the number of targets on the LHS:

super_list = [func(*t) for t in zip(lst_k, lst_r)]
Sign up to request clarification or add additional context in comments.

Comments

4

Sure: parameterise the arguments:

import random
import string

k_val = [3, 7, 4, 3, 1]
r_val = [5, 2, 3, 5, 3]

x = [[(''.join(random.choice(string.ascii_lowercase, k=k_val[i])))
           for _ in range(r_val[i])] for i in range (len(r_val)) ]

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.