向列表的列表中的项目添加概率



我想为列表中的每个项目添加概率,该列表在另一个列表中。

一些psuedo-code:

myList = [ [a, b, c, d], [e, f, g, h], [i, j, k, l], [m, n, o], [p, q, r], [s, t, u] ]
probabilities = [ [0.6, 0.3, 0.075, 0.025], [0.6, 0.3, 0.075, 0.025], [0.6, 0.3, 0.075, 0.025], [0.55, 0.35, 0.1], [0.55, 0.35, 0.1], [0.55, 0.35, 0.1] ]

有什么方法可以做到这一点吗?

进一步:

我的需要是创建另一个列表,看起来类似于下面…

newList = [ [b, e, k, o, p, s], [a, f, i, m, r, t], ... etc. ] 

,其中每个元素都是随机选择的,并且newList中没有两个列表是相同的。我不确定能否实现。

我的代码:

layers = [list(Path(directory).glob("*.png")) for directory in ("dir1/", "dir2/", "dir3/", "dir4/", "dir5/", "dir6/")]
list_of_prob = [[0.6, 0.3, 0.075, 0.025], [0.6, 0.3, 0.075, 0.025], [0.6, 0.3, 0.075, 0.025], [0.6, 0.3, 0.1], [0.6, 0.3, 0.1], [0.6, 0.3, 0.1]]
rwp = [choices(layers, list_of_prob, k=????)]
rand_combinations = [([choice(k) for k in layers]) for i in choice_indices]

我不完全确定选择()中的k是多少,例如列表的数量或列表中总元素的数量。Layers是一个图像路径列表,.png,其格式与"myList"上面提供的伪代码(dir1中有4张图片,dir2中有4张图片,dir3中有4张图片,dir4中有3张图片,dir5中有3张图片,dir6中有3张图片)

我已经有了通过列表迭代并创建随机图像的代码,但我希望一些图像只生成x%的时间。这就是我最初的问题。如果我把事情弄复杂了,我很抱歉,我已经尽力简化了。

为了方便,我将myList转换为字符串。

这将创建组合并将它们附加到newList,忽略newList中已经存在的任何组合

newList的长度等于myList的长度时While循环结束

import random
myList = [['a', 'b', 'c', 'd'], 
['e', 'f', 'g', 'h'], 
['i', 'j', 'k', 'l'], 
['m', 'n', 'o'], 
['p', 'q', 'r'], 
['s', 't', 'u']]
probabilities = [[0.6, 0.3, 0.075, 0.025], 
[0.6, 0.3, 0.075, 0.025], 
[0.6, 0.3, 0.075, 0.025], 
[0.55, 0.35, 0.1], 
[0.55, 0.35, 0.1], 
[0.55, 0.35, 0.1]]
newList = []
def random_list():
combo = []
for d, p in zip(myList, probabilities):
choice = random.choices(d, p)
combo.append(''.join(choice))
return combo
while len(newList) < len(myList):
a = random_list()
if a not in newList:
newList.append(a)

Results of newList:

[['b', 'f', 'k', 'm', 'q', 's'],
['a', 'e', 'j', 'm', 'q', 't'],
['b', 'f', 'k', 'm', 'q', 'u'],
['a', 'f', 'i', 'm', 'p', 's'],
['a', 'e', 'i', 'n', 'p', 't'],
['b', 'f', 'k', 'm', 'r', 'u']]

所以如果我理解正确的话,您希望根据获得元素的概率从myList的每个子列表中获取一个元素,并多次执行此操作以获得列表的列表。

在Python 3中,你可以做:

import random
# the new set since two elements cannot be the same
result_set = set()
# the number of times you want to do it, you can change it.
for i in range(5):
# A single result as a str, hashable.
result = ""
for chars, char_probabilities in zip(myList, probabilities):
# weighted random choice
char = random.choices(chars, char_probabilities)
result += char[0]
result_set.add(result)
result_list = [list(elt) for elt in result_set]

最新更新