Generating random words

2019-07-11 17:58发布

I'm trying to create a string that has a set amount of different words I include in a list, however the code I use only uses one word at random, not a different word for every word printed.

This is my code:

import random

words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print random.choice(words) * 5

An example output would be:

hellohellohellohellohello

An example expected output would be:

appleyeahhellonopesomething

Can anyone tell me what I'm doing wrong?

标签: python random
5条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-11 18:30

"multiplying" a string will print the string multiple times. E.g., print '=' * 30 would print a line of 30 "=", that's why you are getting 5 times "hello" - it repeats the randomly chosen word 5 times.

import random, sys
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']

for i in range(5):
    sys.stdout.write(random.choice(words)) 

using choice() will give you a set of 5 random selections. Note we use sys.std.write to the avoid the space successive print statements would put between words.

e.g., from two runs:

yeahsomethinghelloyeahlalala

and

somethingyeahsomethinglalalanope

choice()

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

Of course in Python 3.x, we could use print instead of sys.stdout.write and set its end value to ''. I.e.,

print(random.choice(words), end='')
查看更多
倾城 Initia
3楼-- · 2019-07-11 18:44

You aren't calling random.choice(words) 5 times, you are getting an output of random.choice(words) and then multiplying in 5 times. With strings, it just repeats the string.

"abc" * 3 would give you "abcabcabc"

So depending on your randomly chosen word first, it just gets repeated 5 times.

查看更多
一纸荒年 Trace。
4楼-- · 2019-07-11 18:45

If you don't want the words from your original list to be repeated, then you could use sample.

import random as rn
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']

word = ''.join(rn.sample(words, 5))

Result:

>>> word
'yeahhellosomethingapplenope'
查看更多
Explosion°爆炸
5楼-- · 2019-07-11 18:51

random.choice(words) * 5 executes random.choice only once and then multiplies the result by five, causing the same string to be repeated.

>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolalala
查看更多
时光不老,我们不散
6楼-- · 2019-07-11 18:52
import random
WORDS = ("Python","Java","C++","Swift","Assembly")
for letter in WORDS:
    position = random.randrange(len(WORDS))
    word = WORDS[position]
    print(word)
查看更多
登录 后发表回答