簡體   English   中英

在Python的列表理解中使用Random

[英]Using Random in Python's list comprehension

我有一個名為words的單詞列表,我想生成一個名為pwds的100個三單詞元素的pwds 我希望從pwds列表的每個元素的words列表中隨機選擇這3個單詞,我想使用列表理解來做到這一點。

此解決方案有效:

pwds = [random.choice(words)+' '+random.choice(words)+' '+random.choice(words) for i in range(0,100)]

它生成的列表看起來像: ['correct horse battery', 'staple peach peach', ...]

但是我一直在尋找一種防止重復3次random.choice(words) ,所以我嘗試了以下方法:

pwds = [(3*(random.choice(words)+' ')).strip() for i in range(0,100)]

但是不幸的是,這種解決方案使每個元素具有相同的單詞3次(例如: ['horse horse horse', 'staple staple staple', ...] ),這是可能發生的。

您是否知道不重復選擇3個隨機單詞的方法(編輯:“重復”,我的意思是代碼重復,而不是隨機單詞重復)

編輯:我的問題不同於它被標記為重復的問題,因為我在這里使用列表理解。 我知道如何生成不同的數字,我只是在尋找實現它的特定方法。

如果您希望單詞能夠在每個三元組中重復出現,我想您想要的是:

pwds = [" ".join(random.choice(words) for _ in range(3)) for _ in range(100)]

請注意,使用_表示我們實際上並沒有使用任何一個range生成的數字,並且range(0, n)range(n)相同。

一個更短的例子:

>>> import random
>>> words = ['correct', 'horse', 'battery', 'staple']
>>> [" ".join(random.choice(words) for _ in range(3)) for _ in range(5)]
['horse horse correct', 
 'correct staple staple', 
 'correct horse horse', 
 'battery staple battery', 
 'horse battery battery']

您可以使用連接功能和列表推導來不重復random.choice

pwds = [' '.join([random.choice(words) for _ in range(3)]) for _ in range(100)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM