gpt4 book ai didi

python - 从任意嵌套列表中随机采样,同时保持结构

转载 作者:行者123 更新时间:2023-11-30 22:22:09 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数从任意嵌套的列表中随机选择整数,同时保持列表的顺序和结构(尽管可以忽略空列表)。样本数应从 0 到嵌套列表中的整数个数均匀随机。

例如,运行 listrand([1,2,3,[3,4],[65,[3]]]) 3 次可能会给出:

[1, 3, [3], [65, [3]]]
[1, 2, [[3]]]
[[3, 4], [65]]

问题是我需要它均匀分布,所以我不能使用类似的东西

sample = [[random.sample(mylist)] for mylist in listoflists]

因为这将是二项式。

至少我需要它来进行单层嵌套。我考虑过从扁平列表中采样,但后来我不确定如何使用它们来构建所需的输出。

最佳答案

该解决方案通过构建满足您的要求。换句话说,选择的元素数量是均匀随机的。

import random
from collections import Iterable

def count(l, r=0):
for i in l:
if isinstance(i, Iterable):
r += count(i)
else:
r += 1
return r

def listrand(target):
N = count(target)
nchosen = random.randint(0, N-1)
chosen = set(random.sample(range(N), nchosen))

def build(l, c=0):
output = []
for i in l:
if isinstance(i, Iterable):
c, sublist = build(i, c)
if sublist:
output.append(sublist)
else:
if c in chosen:
output.append(i)
c += 1
return c, output

return build(target)[1]

示例输出:

target = [1,2,3,[3,4], [65,[3]]]

for i in range(5):
print(listrand(target))

[1, 2, 3, [3, 4], [[3]]]
[2]
[]
[2, 3, [3, 4]]
[[4]]

关于python - 从任意嵌套列表中随机采样,同时保持结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48414404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com