如何在Python中生成随机数对,包括一个条目相同的对,并排除两个条目相同的对? [英] How to generate random pairs of numbers in Python, including pairs with one entry being the same and excluding pairs with both entries being the same?

查看:229
本文介绍了如何在Python中生成随机数对,包括一个条目相同的对,并排除两个条目相同的对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python,并为此使用了numpy. 我想生成随机数对.我想排除两个条目具有相同编号的对的重复结果,并且我想包含只有一个条目具有相同编号的对的结果.我尝试使用

I'm using Python and was using numpy for this. I want to generate pairs of random numbers. I want to exclude repetitive outcomes of pairs with both entries being the same number and I want to include pairs which only have one entry being the same number.I tried to use

import numpy
numpy.random.choice(a,(m,n),replace=False) 

,但是它完全排除了所有具有相同条目的教堂,即

for it, but it excludes any tupels with the the same entries completely, i.e.

import numpy
numpy.random.choice(a=2,(m=2,n=1),replace=False) 

只给我(1,0)和(0,1),不给我(1,1),(0,0),(1,0)和(0,1).

gives me only (1,0) and (0,1) and not (1,1), (0,0), (1,0) and (0,1).

我要这样做是因为我想绘制一个随机的元组样本,该元组具有较大的a和较大的n(如上所用),而又没有获得完全相同的tupel.它也应该或多或少地有效.有没有已经实现此目的的方法?

I want to do this because I want to draw a sample of random tuples with a large a and large n(as used above) without getting exactly the same tupels more then once. It also should be more or less efficient. Is there a way that's already implemented to do this?

推荐答案

生成器随机唯一坐标:

from random import randint

def gencoordinates(m, n):
    seen = set()

    x, y = randint(m, n), randint(m, n)

    while True:
        seen.add((x, y))
        yield (x, y)
        x, y = randint(m, n), randint(m, n)
        while (x, y) in seen:
            x, y = randint(m, n), randint(m, n)

输出:

>>> g = gencoordinates(1, 100)
>>> next(g)
(42, 98)
>>> next(g)
(9, 5)
>>> next(g)
(89, 29)
>>> next(g)
(67, 56)
>>> next(g)
(63, 65)
>>> next(g)
(92, 66)
>>> next(g)
(11, 46)
>>> next(g)
(68, 21)
>>> next(g)
(85, 6)
>>> next(g)
(95, 97)
>>> next(g)
(20, 6)
>>> next(g)
(20, 86)

您可以看到巧合地重复了x坐标!

As you can see coincidentally an x coordinate was repeated!

这篇关于如何在Python中生成随机数对,包括一个条目相同的对,并排除两个条目相同的对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆