简体   繁体   中英

Random word generator python

So this is the code I have. The outcome is something along "['jjjjjjj', 'tt', 'dddd', 'eeeeeeeee']". How can I change the list comprehension to allow for the function random.choice to repeat for each letter of each 'word'?

lista=[random.randint(1,10)*random.choice(string.ascii_letters) for i in range(random.randint(1,10))]

I suppose you mean you want "abcd" and "jdhn" instead of "aaaa" and "jjjj" for the purpose of testing a sorting algorithm or some such.

If so, try this

lista=["".join(random.choice(string.ascii_letters) for j in range(random.randint(1,10)) ) for i in range(random.randint(1,10)) ]

You'll need a nested list comorehension. You need to rerun random.choice for every letter. Something along the lines of

[ [Random.choice(string.asciiletters) for x in range(y)]  for you in range(5)]

Will give you 5 'words' each of length y.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM