目前我的代码返回客户端的名称和visit_length
的随机值。我希望它返回客户名称,然后返回visit_length
中的一个或多个元素,即("Client 1", 15, 45), ("Client 2", 45, 60), ("Client 3", 30)
N = 20
randomitems = []
visit_length = [15, 30, 45, 60]
value_range = np.arange(0, N, 1)
for i in value_range:
visits = ("Client %d" % i, random.choice(visit_length))
randomitems.append(visits)
有什么建议吗?我以为随机库中可能有东西,但我还没有找到任何东西。
谢谢!
答案 0 :(得分:2)
选择要随random.randint
追加的项目的随机数visit_length
,然后将import random
import numpy as np
N = 20
randomitems = []
visit_length = [15, 30, 45, 60]
value_range = np.arange(0, N, 1)
for i in value_range:
k = random.randint(1, len(visit_length))
visits = ("Client %d" % i,) + tuple(sorted(random.sample(visit_length, k=k)))
randomitems.append(visits)
中的元素数量与random.sample
一起使用。
import random
import numpy as np
N = 20
MAX_VISIT_LENGTHS = 4 # You can choose as many as you want now I guess
randomitems = []
visit_length = [15, 30, 45, 60]
value_range = np.arange(0, N, 1)
for i in value_range:
k = random.randint(1, MAX_VISIT_LENGTHS)
vs = sorted(random.choice(visit_length) for _ in range(k))
# If you do not want to sort use
# vs = [random.choice(visit_length) for _ in range(k)]
visits = ("Client %d" % i,) + tuple(vs)
randomitems.append(visits)
如果您想允许重复的项目:
echo "c:\tmp\$(TestCaseID)\$(repoZipExtractedName)\windows_downloader.bat -
configFile c:\tmp\$(TestCaseID)/$(OfflineDownloader_FileName)" > //$(repoServer)/c/tmp/$(TestCas eID)/execute.bat
答案 1 :(得分:1)
更新回答以返回元组
我可能误解了你想要的东西,但这是我对这个问题的看法: 我们创建一个函数,从列表x返回一个随机数量的项目(在1-4 = N之间)并以随机顺序返回它们。
import random
def visits_func():
N = random.randint(1, 4)
x = [15, 30, 45, 60]
y = []
while N:
y.append(x.pop(random.randrange(len(x))))
N -= 1
return y
value_range = range(1,6) #1,2,3,4,5,6
randomitems = []
for i in value_range:
visits = tuple(["Client %d" % i] + sorted(visits_func()))
randomitems.append(visits)
打印,例如
[('Client 1', 15, 60),
('Client 2', 15),
('Client 3', 45, 60),
('Client 4', 30, 60),
('Client 5', 15, 30, 45)]