How can I generate a unique ID in Python? [duplica

2019-01-10 06:01发布

This question already has an answer here:

I need to generate a unique ID based on a random value.

9条回答
Summer. ? 凉城
2楼-- · 2019-01-10 06:34
import time
def new_id():
    time.sleep(0.000001)
    return time.time()

On my system, time.time() seems to offer 6 significant figures after the decimal point. With a brief sleep it should be guaranteed unique with at least a moderate amount of randomness down in the last two or three digits.

You could hash it as well if you're worried.

查看更多
Emotional °昔
3楼-- · 2019-01-10 06:36

You might want Python's UUID functions:

21.15. uuid — UUID objects according to RFC 4122

eg:

import uuid
print uuid.uuid4()

7d529dd4-548b-4258-aa8e-23e34dc8d43d

查看更多
冷血范
4楼-- · 2019-01-10 06:41

Perhaps uuid.uuid4() might do the job. See uuid for more information.

查看更多
Rolldiameter
5楼-- · 2019-01-10 06:43
import time
import random
import socket
import hashlib

def guid( *args ):
    """
    Generates a universally unique ID.
    Any arguments only create more randomness.
    """
    t = long( time.time() * 1000 )
    r = long( random.random()*100000000000000000L )
    try:
        a = socket.gethostbyname( socket.gethostname() )
    except:
        # if we can't get a network address, just imagine one
        a = random.random()*100000000000000000L
    data = str(t)+' '+str(r)+' '+str(a)+' '+str(args)
    data = hashlib.md5(data).hexdigest()

    return data
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-10 06:45

unique and random are mutually exclusive. perhaps you want this?

import random
def uniqueid():
    seed = random.getrandbits(32)
    while True:
       yield seed
       seed += 1

Usage:

unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))

no two returned id is the same (Unique) and this is based on a randomized seed value

查看更多
时光不老,我们不散
7楼-- · 2019-01-10 06:46

Maybe the uuid module?

查看更多
登录 后发表回答