Home > Mobile >  How to generate a range of random lists from given letters instead of only one list?
How to generate a range of random lists from given letters instead of only one list?

Time:02-05

I have a list of 10 letters and I want to generate 100 random rows of 5 characters using these letters. Here, I could form one random list; however I need to form 100 random lists.

import random  
import string  
def random_list(length):  
    letters = 'pqrstuvwxy'     
    result = ''.join((random.choice(letters)) for x in range(length))  
    print("List1\n",result)   
    
random_list(5)

The output of the above code is:

List1
 wyquq

What I want to do is to generate a .txt file in this format:

List1
wyquq
List2
qrrxw
List3
ysrvs
...

CodePudding user response:

I guess this is what you want .

import random  
import string  
def random_list(length, rows=100):
    letters = 'pqrstuvwxy'
    return [''.join((random.choice(letters)) for _ in range(length)) for _ in range(rows)]


rows = 10
randomList = random_list(5, rows)
output=""
counter=0
for element in randomList:
    counter =1
    output  = "List" str(counter) "\n" element "\n"

print(output)

CodePudding user response:

It was missing the iteration over the amount of rows

def random_list(length, rows=100):
    letters = 'pqrstuvwxy'
    return [''.join(random.choice(letters) for _ in range(length)) 
                                             for _ in range(rows)]

# saving to a file
path = # your path

with open(path, 'w') as fd:
    print(*random_list(5, 10), sep='\n', file=fd)

    # or fd.write('\n'.join(random_list(5, 10)))

Use _ in a iteration when the iteration variable is not used.


Adding a "title" at each line

pattern = "List{}\n{}\n"

random_strs = ''.join(pattern.format(i, word) for i, word in enumerate(random_list(5, 10), 1))

with open(path, 'w') as fd:
    fd.write(random_strs)
  • Related