生成随机词 [英] Generating random words

查看:40
本文介绍了生成随机词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个字符串,其中包含我包含在列表中的一组不同单词,但是我使用的代码仅随机使用一个单词,而不是每个打印的单词都使用不同的单词.

这是我的代码:

随机导入words = ['你好', 'apple', 'something', 'yeah', 'nope', 'lalala']打印 random.choice(words) * 5

示例输出为:

hellohellohellohellohello

预期输出示例如下:

appleyeahhellonopesomething

谁能告诉我我做错了什么?

解决方案

random.choice(words) * 5 只执行一次 random.choice 然后将结果相乘5,导致重复相同的字符串.

<预><代码>>>>随机导入>>>words = ['你好', 'apple', 'something', 'yeah', 'nope', 'lalala']>>>打印 ''.join(random.choice(words) for _ in range(5))苹果东西你好你好啦啦啦

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?

解决方案

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

这篇关于生成随机词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆