繁体   English   中英

如何使用与特定数字不匹配的对创建两个随机列表?

[英]How do I create two random lists with pairs that do not match specific numbers?

我有 2 个随机数列表,范围从 0 到 7,我想配对

listA = random.sample(range(8), 8)
listB = random.sample(range(8), 8)

但是,我想确保 listA 中的数字 1 永远不会与其自身或 listB 中的数字 4 配对。

for a,b in zip (listA, listB):
  if a==b:
    random.shuffle(giver)
  if a==1 and b==4:
    random.shuffle(giver)

我如何确保我的列表满足这两个条件?

感谢您的时间!

我想出了这个:

import itertools
import random

list_a = random.sample(range(8), 8)
list_b = random.sample(range(8), 8)
it1 = itertools.cycle(list_a)
it2 = itertools.cycle(list_b)


def gen_pairs():
    count = 0
    while count < 8:
        x, y = next(it1), next(it2)
        if y == list_a[1] or x == list_b[4]:
            continue

        yield x, y
        count += 1


print(list_a[1])
print(list_b[4])

for _ in range(20):
    res = list(gen_pairs())
    assert (list_a[1], list_a[1]) not in res
    assert (list_b[4], list_b[4]) not in res

我希望我理解正确,这有帮助:

import random

listA = random.sample(range(8), 8)
listB = random.sample(range(8), 8)

## This first search is just for listA[0]
zipped_list = []
good_match = False
while good_match == False:
    candidate = random.choice(listB)
    if listA[0] != candidate and listA[0] != listB[3]:
        zipped_list.append([listA[0], candidate])
        good_match = True

## Now we find numbers to match with the rest of listA
for num in listA[1:]:
    good_match = False
    while (good_match == False):
        candidate = random.choice(listB)
        if num != candidate:
            zipped_list.append([num, candidate])
            good_match = True
            
print(zipped_list)

输入示例:

listA: [7, 4, 2, 1, 3, 0, 5, 6]
listB: [0, 3, 5, 1, 4, 2, 7, 6]

输出示例: listA (7) 的第一个元素与 listB[0] 或 listB[4] 不匹配,其他数字与自身不匹配。

[[7, 1], [4, 1], [2, 6], [1, 0], [3, 2], [0, 2], [5, 2], [6, 2]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM