簡體   English   中英

python:獲取隨機值在列表中不存在

[英]python : get random value not exist in list

我有以下代碼:

def random_generate(list)
    x = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    x = list(x)
    random = choice(x)+choice(x)+choice(x)

其中list是3個字符的字符串的列表,例如["abc","acd","aza"] ,我這樣調用我的函數:

random_generate(["abc", "acd", "aza"])

我想使用x字符來random生成一個3個字符的字符串,但是不在list ,例如"aef"

我知道我可以進行循環,直到得到不在list的字符串,但這不是很有效。 有人可以為我提供一些有關如何生成不在list的字符串的提示嗎?

您可以使用一組存儲已采集的樣本:

def random_generate(lst):
    x = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    st = set(lst)
    samp = choice(x)+choice(x)+choice(x)
    while samp in st:
        samp = choice(x)+choice(x)+choice(x)
    return samp

或一次生成所有長度為3的子字符串,並在每次運行代碼時隨機選擇一個子字符串,如果實際樣本量大得多,則刪除選擇的子序列並保留數據(如果只有64)選擇3(帶替換),則保留將花費更長的時間而不是每次都簡單地創建數據集並使用set.difference獲得尚未使用的值:

from itertools import combinations_with_replacement

data =  combinations_with_replacement('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',3)

在我的筆記本上花費3.09 ms來生成所有可能的三個字符子序列的列表。

附帶說明一下,不要將list用作變量名,因為它位於您自己的代碼list(x) ,因為陰影了內置list會出錯

使用該函數創建包含接近10k個隨機子字符串的列表,可以非常有效地生成唯一的子字符串:

In [18]:  x = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' 
In [19]: l = [choice(x)+choice(x)+choice(x) for _ in range(10000)]

In [20]: len(set(l))
Out[20]: 9863

In [21]: timeit random_generate(l)
1000 loops, best of 3: 432 µs per loop

即使最壞的情況,首先生成所有組合的集合並從集合的差中獲取隨機值也要花費毫秒:

def random_generate_comb(lst):
    x = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    data =  set(combinations_with_replacement(x,3))
    return "".join(choice(list(data.difference(lst))))

In [23]: timeit random_generate_comb(l)
100 loops, best of 3: 15.2 ms per loop

因此,除非您的樣本數量比您顯示的要大得多,否則任何一種方法都應該足夠。

您必須更新功能:

import random
from string import ascii_letters,digits

def random_generate(in_list):
    x = ascii_letters + digits + '+/'
    random_ = ''.join(list((random.choice(x) for num in range(3))))
    while random_ in in_list:
        random_ = ''.join(list((random.choice(x) for num in range(3))))
    print(random_)

函數保證返回的字符串不同於in_list中的項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM