如何验证 UUID 列表并返回 UUID 版本? [英] How to validate list of UUID's AND return UUID Version?
问题描述
我需要验证 UUID 列表并确定版本.例如,使用 https://www.beautifyconverter.com/uuid-validator.php 并输入 25CCCA6F-1568-473E-BFED-EC08C31532C6 我可以确定它是有效的,并且是版本 4.我从 https://www.snip2code.com/Snippet/12614/Validating-a-uuid4-with-Python- 和 如何确定一个字符串是否是有效的 v4 UUID? UUID 模块可以一次验证一个,或测试特定版本,但不确定 UUID 是否会测试所有 4 个版本并返回版本.
I'm needing to both validate a list of UUID's as well as determine the version. For example, using https://www.beautifyconverter.com/uuid-validator.php and entering 25CCCA6F-1568-473E-BFED-EC08C31532C6 I can determine that it is both valid, and version 4. I see from https://www.snip2code.com/Snippet/12614/Validating-a-uuid4-with-Python- and How to determine if a string is a valid v4 UUID? that the UUID module can validate one at a time, or test for a particular version, but not sure if UUID will test for all 4 versions and return the version.
推荐答案
这里是我如何迭代潜在的 UUID 列表并返回带有版本号(如果有效)或 None的并行列表代码>否则.
Here is how I would iterative over a list of potential UUIDs and return a parallel list with either the version number (if valid) or None
otherwise.
特别注意 UUID
构造函数接受任何版本的 UUID 字符串.如果字符串有效,您可以查询 .version
成员以确定版本.
Note especially that the UUID
constructor accepts UUID strings of any version. If the string is valid, you can query the .version
member to determine the version.
from uuid import UUID
def version_uuid(uuid):
try:
return UUID(uuid).version
except ValueError:
return None
def version_list(l):
return [version_uuid(uuid) for uuid in l]
if __name__=="__main__":
uuids = (
'0d14fbaa-8cd6-11e7-b2ed-28d244cd6e76',
'6fa459ea-ee8a-3ca4-894e-db77e160355e',
'16583cd3-8361-4fe6-a345-e1f546b86b74',
'886313e1-3b8a-5372-9b90-0c9aee199e5d',
'0d14fbaa-8cd6-11e7-b2ed-28d244cd6e7',
'6fa459ea-ee8a-3ca4-894e-db77e160355',
'16583cd3-8361-4fe6-a345-e1f546b86b7',
'886313e1-3b8a-5372-9b90-0c9aee199e5',
'481A8DE5-F0D1-E211-B425-E41F134196DA',
)
assert version_list(uuids) == [1,3,4,5,None,None,None,None,14]
这篇关于如何验证 UUID 列表并返回 UUID 版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!