如何一次对列表中的 2 个随机元素运行循环?
假设我有一个 python 列表,其中有几个字符串。我不知道尺寸。如何运行循环来对该字符串的 2 个随机元素执行操作?
如果我想在随机化中更频繁地选择字符串的某个子集,但仍然有可能不选择它们,该怎么办?
Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string?
What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for them to not be chosen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要查看
random
模块。例如,它有一个random.choice
函数,可让您从序列中选择一个随机元素或random.sample
选择给定数量的样本,也很容易考虑不同的权重。you need to look into
random
module. It has for example arandom.choice
function that lets you select a random element from a sequence or arandom.sample
that selects given number of samples, it's easy to account for different weights too.更好地解释您的问题,您关注哪些操作和哪些元素?
关于更频繁地选择元素的问题,给每个字符串一个“机会乘数”,每次比较时将 1 到 10 之间的数字与字符串的机会乘数相乘,如果结果高于 X(例如... 5),因此它选择该字符串,如果没有,则搜索另一个字符串。这样,乘数越高的字符串将有更多的机会被选择
explain better your problem, what operations and what elements you're focusing?
regarding the problem with the elements beeing chosen more often, give each string an "chance multiplier", each comparison you multiply a number between 1 and 10 and the chance multiplyer of the string, if the result is higher than X (say... 5), so it select the string, if not, it searches for another string. this way, strings with higher multipliers will have more chance to be selected