【问题标题】:Generate a list random numbers eliminating the random numbers in another list in Python [closed]生成一个列表随机数,消除 Python 中另一个列表中的随机数 [关闭]
【发布时间】:2021-01-06 14:06:36
【问题描述】:

我想生成第一个列表中不存在的随机数列表。保持列表的大小与第一个相似。我已经完成了 R 如下。 示例:

bb

bb

[1] 11 19 23 15 25 12 14 21 10 4

wd

wd

[1] 13 1 5 9 22 3 2 24 7 16

我希望在 python 中复制相同的内容。试了好几种方法都没用。

请帮助..提前感谢

【问题讨论】:

  • Stack Overflow 是一个问答网站,而不是代码翻译服务。尝试先自己翻译代码,然后在遇到困难时来找我们,确保向我们展示您尝试过的内容并创建minimal reproducible example
  • 如果没有看到您的原始代码,我们将不知道如何对您现有的代码库进行更改。请发minimal reproducible example,并详细说明需要修改的地方。

标签: python numpy random


【解决方案1】:

你可以试试这样的:

import random

l1 = [11, 19, 23, 15, 25, 12, 14, 21, 10, 4]
l2 = []

while len(l2) < len(l1):
    while True:
        r = random.randint(1, 25)
        if r not in l1 and r not in l2: 
            l2.append(r)
            break
        
print(l2) #==> [16, 20, 2, 9, 3, 18, 6, 24, 17, 7]

【讨论】:

  • @Patrick Artner:你说得对,我解决了这个问题。对于你的第二句话,我不知道这个问题是题外话,对不起。
  • 哎呀...我自然忘记了,谢谢!
【解决方案2】:

假设您没有测试列表,您可以使用 python 中 random 模块的 sample 函数,它会为您提供一个唯一的元素列表您喜欢的范围和相应的编号。所需的元素。

您还可以使用简单的 while 循环if 条件 来确保没有重复项被插入到第二个列表中。

相同的代码示例如下:

import random

n = int(input("Enter the length of the required list: "))

l1=random.sample(range(1,100), n)

l2=[]
while len(l2) < len(l1):
    while True:
        r = round(random.randint(1, 100))
        if r not in l1 and r not in l2: 
            l2.append(r)
            break

print("List 1: ",l1) 
print("List 2: ",l2)

理想情况下,您每次运行此脚本时都会获得两个唯一列表。

样本输出:

List 1:  [14, 80, 55, 88, 4, 30, 82, 95, 23, 93]
List 2:  [49, 64, 78, 87, 8, 79, 31, 28, 51, 92]

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 2013-04-22
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多