如何生成与历史值不重复的十六进制值?基于os.urandom的求助
os.urandom Got it, let's tackle this problem. You're generating 1-byte hex values using os.urandom(1) and need 15 unique ones—totally feasible since there are 256 possible distinct values (way more than 15), so duplicates are extremely unlikely, but we can guarantee no repeats with a few straightforward approaches.
Method 1: Use a Set to Track Unique Values
Sets automatically ignore duplicate entries, making this the simplest approach. We'll keep generating values until our set has 15 unique entries:
import os import binascii unique_hex_values = set() # Keep generating until we have 15 unique values while len(unique_hex_values) < 15: # Generate 1 byte, convert to hex, and decode to a string hex_val = binascii.b2a_hex(os.urandom(1)).decode('utf-8') unique_hex_values.add(hex_val) # Convert to a list if you need ordered values unique_list = list(unique_hex_values) print(unique_list)
Why this works:
- Sets in Python don't allow duplicate elements, so calling
add()with an existing value does nothing. - Since there are 256 possible 1-byte hex values, this loop will exit almost instantly—no risk of infinite looping here.
Method 2: Pre-Generate All Possible Values & Randomly Select
Since the total number of possible 1-byte hex values is small (256), we can generate all of them first, shuffle the list, then pick the first 15. This avoids looping entirely:
import binascii import random # Generate every possible 1-byte hex value all_possible_hex = [binascii.b2a_hex(bytes([i])).decode('utf-8') for i in range(256)] # Shuffle the list randomly random.shuffle(all_possible_hex) # Grab the first 15 unique values unique_list = all_possible_hex[:15] print(unique_list)
For Cryptographically Secure Randomness:
If you need the shuffle to match the security level of os.urandom, replace random.shuffle with secrets.SystemRandom().shuffle (Python 3.6+):
import binascii import secrets all_possible_hex = [binascii.b2a_hex(bytes([i])).decode('utf-8') for i in range(256)] secrets.SystemRandom().shuffle(all_possible_hex) unique_list = all_possible_hex[:15] print(unique_list)
Which Method to Choose?
- Use Method 1 if you want a minimal, intuitive solution that directly uses
os.urandomfor each value. - Use Method 2 if you prefer to avoid loops, or if you need to work with a fixed pool of possible values.
Both approaches will reliably give you 15 unique 1-byte hex values.
内容的提问来源于stack exchange,提问作者Hunter.S.Thompson

