簡體   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