【问题标题】:How do I create two random lists with pairs that do not match specific numbers?如何创建两个随机列表,其中包含与特定数字不匹配的对?
【发布时间】:2021-10-04 15:19:55
【问题描述】:

我有 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)

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

感谢您的宝贵时间!

【问题讨论】:

  • 如果我理解正确的话,你想有两个列表,listA[1] != listB[4]listA[1] != listB[1] 吗?
  • @Andrej Kesely 正确!

标签: python list for-loop if-statement


【解决方案1】:

我想出了这个:

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

【讨论】:

    【解决方案2】:

    我希望我理解正确并且这对您有帮助:

    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]]
    

    【讨论】:

    • 我已经看到了改进的潜力。我认为我们需要确保 listB 的元素不会被多次选中。我说的对吗?
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 2022-11-14
    • 2021-08-26
    • 2017-06-06
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多